rubyasynchronousioeventmachine

Sleep with EventMachine


I'm trying EventMachine and have an simple server:

require 'eventmachine'                                                                                                     

module Handler                                                                                                             
  def receive_data(data)                                                                                                   
    send_data "#{Time.now}: Received data: #{data}"                                                                        
    sleep 3                                                                                                                
    send_data "#{Time.now}: Message after 3 seconds\r\n"                                                                   
  end                                                                                                                      
end                                                                                                                        

EventMachine.run do                                                                                                        
  EventMachine.start_server('0.0.0.0', 1234, Handler)                                                                      
end

When I run the server and connect to it via telnet I have the following:

root@edfe43af3db3:/# telnet localhost 1234
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
hello world
2017-12-13 05:35:26 +0000: Received data: hello world
2017-12-13 05:35:29 +0000: Message after 3 seconds

It seems fine but it behaves in an unexpected way. When I send hello world to the server I expect to get back Received data: hello world message practically at the same time and after 3 seconds I expect to get Message after 3 seconds message. But now after sending a command to server at first I get back nothing and after 3 seconds I get two messages together.

How can I achieve desired manner?


Solution

  • Don't use sleep, use a timer.

    require 'eventmachine'
    
    module Handler
      def receive_data(data)
        send_data "#{Time.now}: Received data: #{data}"
        EventMachine::Timer.new(3) do
          send_data "#{Time.now}: Message after 3 seconds\r\n"
        end
      end
    end
    
    EventMachine.run do
      EventMachine.start_server('127.0.0.1', 1234, Handler)
    end