使用EventMachine进行睡眠

时间:2017-12-13 05:44:16

标签: ruby asynchronous io eventmachine

我尝试使用EventMachine并拥有一个简单的服务器:

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

当我运行服务器并通过telnet连接到它时,我有以下内容:

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

看起来很好,但它表现得出乎意料。当我将hello world发送到服务器时,我希望几乎同时收到Received data: hello world消息,并且在3秒后我希望得到Message after 3 seconds消息。但是现在在向服务器发送命令之后我什么都没回来,3秒后我得到两条消息。

我如何达到理想的方式?

1 个答案:

答案 0 :(得分:2)

不要使用睡眠,请使用计时器。

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