Sha256: d628b452efa4909abdac426b4726e2cd3d9cbcfd07fbaba44ceade8557cad8e9

Contents?: true

Size: 1.02 KB

Versions: 26

Compression:

Stored size: 1.02 KB

Contents

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

$LOAD_PATH.push File.expand_path("../lib", __dir__)
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 }
    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

26 entries across 23 versions & 5 rubygems

Version Path
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/nio4r-2.5.8/examples/echo_server.rb
nio4r-2.6.0-java examples/echo_server.rb
nio4r-2.6.0 examples/echo_server.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/nio4r-2.5.8/examples/echo_server.rb
nio4r-2.5.9-java examples/echo_server.rb
nio4r-2.5.9 examples/echo_server.rb
date_n_time_picker_activeadmin-0.1.2 vendor/bundle/ruby/2.6.0/gems/nio4r-2.5.8/examples/echo_server.rb
date_n_time_picker_activeadmin-0.1.1 vendor/bundle/ruby/2.6.0/gems/nio4r-2.5.8/examples/echo_server.rb
rails_mini_profiler-0.2.0 vendor/bundle/ruby/3.0.0/gems/nio4r-2.5.7/examples/echo_server.rb
nio4r-2.5.8-java examples/echo_server.rb
nio4r-2.5.8 examples/echo_server.rb
tdiary-5.1.6 vendor/bundle/ruby/2.7.0/gems/tdiary-5.1.5/vendor/bundle/ruby/3.0.0/gems/nio4r-2.5.5/examples/echo_server.rb
tdiary-5.1.6 vendor/bundle/ruby/2.7.0/gems/nio4r-2.5.7/examples/echo_server.rb
tdiary-5.1.6 vendor/bundle/ruby/2.7.0/gems/tdiary-5.1.5/vendor/bundle/ruby/3.0.0/gems/nio4r-2.5.4/examples/echo_server.rb
nio4r-2.5.7-java examples/echo_server.rb
nio4r-2.5.7 examples/echo_server.rb
nio4r-2.5.6-java examples/echo_server.rb
nio4r-2.5.6 examples/echo_server.rb
tdiary-5.1.5 vendor/bundle/ruby/3.0.0/gems/nio4r-2.5.4/examples/echo_server.rb
tdiary-5.1.5 vendor/bundle/ruby/3.0.0/gems/nio4r-2.5.5/examples/echo_server.rb