daily pastebin goal
69%
SHARE
TWEET

Untitled

a guest Jan 13th, 2018 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env ruby
  2. # frozen_string_literal: true
  3.  
  4. $LOAD_PATH.push File.expand_path("../../lib", __FILE__)
  5. require "nio"
  6. require "socket"
  7.  
  8. # Echo server example written with nio4r
  9. class EchoServer
  10.   def initialize(host, port)
  11.     backend = ENV["NIO4R_PURE"] ? :ruby : nil
  12.     @selector = NIO::Selector.new backend
  13.     puts "use backend #{@selector.backend}"
  14.  
  15.     puts "Listening on #{host}:#{port}"
  16.     @server = TCPServer.new(host, port)
  17.  
  18.     monitor = @selector.register(@server, :r)
  19.     monitor.value = proc { accept }
  20.     @monitor = monitor
  21.   end
  22.  
  23.   def run
  24.     loop do
  25.       # printing server readiness
  26.       puts "server readiness is #{ @monitor.readiness}"
  27.       @selector.select { |monitor| monitor.value.call(monitor) }
  28.     end
  29.   end
  30.  
  31.   def accept
  32.     socket = @server.accept
  33.     _, port, host = socket.peeraddr
  34.     puts "*** #{host}:#{port} connected"
  35.  
  36.     monitor = @selector.register(socket, :r)
  37.     monitor.value = proc { read(socket) }
  38.   end
  39.  
  40.   def read(socket)
  41.     data = socket.read_nonblock(4096)
  42.     socket.write_nonblock(data)
  43.   rescue EOFError
  44.     _, port, host = socket.peeraddr
  45.     puts "*** #{host}:#{port} disconnected"
  46.  
  47.     @selector.deregister(socket)
  48.     socket.close
  49.   end
  50. end
  51.  
  52. EchoServer.new("localhost", 1234).run if $PROGRAM_NAME == __FILE__
RAW Paste Data
Top