与 EventMachine 一起睡觉

Sleep with 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 秒后,我收到了两条消息。

我怎样才能达到我想要的方式?

不要使用睡眠,使用定时器。

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