Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 与EventMachine一起睡觉_Ruby_Asynchronous_Io_Eventmachine - Fatal编程技术网

Ruby 与EventMachine一起睡觉

Ruby 与EventMachine一起睡觉,ruby,asynchronous,io,eventmachine,Ruby,Asynchronous,Io,Eventmachine,我正在尝试EventMachine,它有一个简单的服务器: require 'eventmachine' module Handler

我正在尝试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
时,我希望在同一时间收到
收到的数据:hello world
消息,3秒钟后我希望在3秒钟后收到
消息。但现在,在向服务器发送命令后,我一开始什么也没得到,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

您不能先执行
put
而不是
send\u data
呼叫吗?当然可以,但它只在服务器端打印行。但我想立即在客户端收到这条消息,3秒钟后在客户端收到第二条消息。谢谢。这是我想要的