Sha256: 9d188ffc213df49ab616641d255996cfd7355a803df16923cd21e7d353041ab9

Contents?: true

Size: 981 Bytes

Versions: 26

Compression:

Stored size: 981 Bytes

Contents

#!/usr/bin/env ruby

$:.push File.expand_path('../../lib', __FILE__)
require 'nio'
require 'socket'

class EchoServer
  def initialize(host, port)
    @selector = NIO::Selector.new

    puts "Listening on #{host}:#{port}"
    @server = TCPServer.new(host, port)

    monitor = @selector.register(@server, :r)
    monitor.value = proc { accept }
  end

  def run
    while true
      @selector.select { |monitor| monitor.value.call(monitor) }
    end
  end

  def accept
    socket = @server.accept
    _, port, host = socket.peeraddr
    puts "*** #{host}:#{port} connected"

    monitor = @selector.register(socket, :r)
    monitor.value = proc { read(socket) }
  end

  def read(socket)
    data = socket.read_nonblock(4096)
    socket.write_nonblock(data)
  rescue EOFError
    _, port, host = socket.peeraddr
    puts "*** #{host}:#{port} disconnected"

    @selector.deregister(socket)
    socket.close
  end
end

if $0 == __FILE__
  EchoServer.new("localhost", 1234).run
end

Version data entries

26 entries across 26 versions & 1 rubygems

Version Path
nio4r-1.1.0 examples/echo_server.rb
nio4r-1.1.0-java examples/echo_server.rb
nio4r-1.0.1-java examples/echo_server.rb
nio4r-1.0.1 examples/echo_server.rb
nio4r-1.0.0-java examples/echo_server.rb
nio4r-1.0.0 examples/echo_server.rb
nio4r-0.5.0-java examples/echo_server.rb
nio4r-0.5.0 examples/echo_server.rb
nio4r-0.4.6-java examples/echo_server.rb
nio4r-0.4.6 examples/echo_server.rb
nio4r-0.4.5-java examples/echo_server.rb
nio4r-0.4.5 examples/echo_server.rb
nio4r-0.4.4-java examples/echo_server.rb
nio4r-0.4.4 examples/echo_server.rb
nio4r-0.4.3 examples/echo_server.rb
nio4r-0.4.3-java examples/echo_server.rb
nio4r-0.4.2 examples/echo_server.rb
nio4r-0.4.2-java examples/echo_server.rb
nio4r-0.4.1-java examples/echo_server.rb
nio4r-0.4.1 examples/echo_server.rb