我正在使用 em-websocket gem 制作一个 Ruby 服务器。当客户端发送一些消息(例如“线程”)时,服务器会创建两个不同的线程并将两个 anwsers 并行发送到客户端(我实际上正在研究多线程和 websockets)。这是我的代码:
EM.run {
EM::WebSocket.run(:host => "0.0.0.0", :port => 8080) do |ws|
ws.onmessage { |msg|
puts "Recieved message: #{msg}"
if msg == "thread"
threads = []
threads << a = Thread.new {
sleep(1)
puts "1"
ws.send("Message sent from thread 1")
}
threads << b = Thread.new{
sleep(2)
puts "2"
ws.send("Message sent from thread 2")
}
threads.each { |aThread| aThread.join }
end
它是如何执行的:
- 我正在向服务器发送“线程”消息
- 在我的控制台中一秒钟后,我看到打印的字符串“1”。又过了一秒钟,我看到“2”。
- 只有在那之后,两条消息才会同时发送到客户端。
问题是我想在发送调试输出“1”和“2”的同时发送消息。
我的 Ruby 版本是 1.9.3p194。