Sha256: 463e678338c168ffa1028eee4cbb8f8378e054c3a89fb9b7e51daf1d3ec4bd69

Contents?: true

Size: 1.04 KB

Versions: 27

Compression:

Stored size: 1.04 KB

Contents

#!/usr/bin/env ruby
# frozen_string_literal: true

$LOAD_PATH.push File.expand_path("../../lib", __FILE__)
require "nio"
require "socket"

# Echo server example written with nio4r
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
    loop do
      @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

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

Version data entries

27 entries across 27 versions & 7 rubygems

Version Path
tdiary-5.1.2 vendor/bundle/ruby/2.6.0/gems/nio4r-2.5.2/examples/echo_server.rb
argon-1.3.1 vendor/bundle/ruby/2.7.0/gems/nio4r-2.5.2/examples/echo_server.rb
symbolic_enum-1.1.5 vendor/bundle/ruby/2.7.0/gems/nio4r-2.5.2/examples/echo_server.rb
tdiary-5.1.1 vendor/bundle/ruby/2.6.0/gems/nio4r-2.5.2/examples/echo_server.rb
chatops-rpc-0.0.2 fixtures/chatops-controller-example/vendor/bundle/ruby/2.5.0/gems/nio4r-2.5.2/examples/echo_server.rb
chatops-rpc-0.0.1 fixtures/chatops-controller-example/vendor/bundle/ruby/2.5.0/gems/nio4r-2.5.2/examples/echo_server.rb
nio4r-2.5.2-java examples/echo_server.rb
nio4r-2.5.2 examples/echo_server.rb
nio4r-2.5.1-java examples/echo_server.rb
nio4r-2.5.1 examples/echo_server.rb
nio4r-2.5.0-java examples/echo_server.rb
nio4r-2.5.0 examples/echo_server.rb
spiral_form-0.1.1 vendor/bundle/gems/nio4r-2.4.0/examples/echo_server.rb
spiral_form-0.1.0 vendor/bundle/gems/nio4r-2.4.0/examples/echo_server.rb
nio4r-2.4.0-java examples/echo_server.rb
nio4r-2.4.0 examples/echo_server.rb
nio4r-2.3.1-java examples/echo_server.rb
nio4r-2.3.1 examples/echo_server.rb
nio4r-2.3.0-java examples/echo_server.rb
nio4r-2.3.0 examples/echo_server.rb