practicingruby/rbp-book

TCPserver issue in example

Closed this issue · 1 comments

dgm commented

page 46, the TCPServer doesn't work as expected. To handle multiple lines of input, it needs to loop on the session.gets, and it would be good form to close the session afterwards.

Just for fun, I also added the ability to close the connection and shut down the server from the client:

require 'socket'
class Server 
  def initialize(port=3333) 
    @server   = TCPServer.new('127.0.0.1',port) 
    @handlers = {} 
  end 
  def handle(pattern, &block) 
    @handlers[pattern] = block 
  end 
  def run 
    @shutdown = false
    while !@shutdown and session = @server.accept 
    @running = true
     while @running and msg = session.gets 
        match = nil 
        @handlers.each do |pattern,block|
          if match = msg.match(pattern)
            instance_eval &block
            break session.puts(block.call(match))
          end 
        end 
        unless match 
          session.puts "Server received unknown message: #{msg}" 
        end 
      end
    session.close
    end 
  end 
end 


server = Server.new 
server.handle(/hello/i) { "Hello from server at #{Time.now}" } 
server.handle(/goodbye/i) { @running = false ; "Goodbye from server at #{Time.now}" } 
server.handle(/name is (\w+)/) { |m| "Nice to meet you #{m[1]}!" } 
server.handle(/shutdown/) {@shutdown = true ; "Shutting down now, Goodbye"}
server.run 
dgm commented

ah, I see, if you just use the client, the client shuts down. I was testing by hand with telnet.