我想使用ruby语言gem-em-websocket:https://github.com/igrigorik/em-websocket在eventmachine上运行websocket服务器。
我成功地运行了echo服务器演示:
EM.run {
EM::WebSocket.run(:host => "0.0.0.0", :port => 8080) do |ws|
ws.onopen { |handshake|
puts "WebSocket connection open"
ws.send "Hello Client, you connected to #{handshake.path}"
}
ws.onclose { puts "Connection closed" }
ws.onmessage { |msg|
puts "Recieved message: #{msg}"
ws.send "Pong: #{msg}"
}
end
}
现在我想开发一个演示,服务器可以通过websocket消息每隔n毫秒(随机值)将一些数据推送到连接的客户端。。。实际上类似于:
def periodic_push
# random elapsed: from 100 milliseconds to 6 seconds
msec_value = (rand(100..6000) / 1000.0 )
message = "time: #{Time.now} value: #{msec_value.to_s}"
ws.send message
puts message
sleep (msec_value)
end
我知道我不能在EM循环中使用sleep()系统调用,但我不知道如何在CCD_ 1中插入周期性事件;也许是EventMachine::PeriodicTimer
?怎样
有人可以帮我做一个代码示例chunck吗?谢谢乔治
我自己找到了一个解决方案:在下面的代码中,服务器每500毫秒向客户端推送一条websocket消息。(PeriodicTimer.new(0.5))。
我现在的问题是,如何定期重置计时器,以每N毫秒发送一条消息,其中N是一个随机值。。。知道吗
require 'eventmachine'
require 'em-websocket'
require 'socket'
EM.run {
EM::WebSocket.run(:host => "0.0.0.0", :port => 8080) do |ws|
ws.onopen { |handshake|
puts "WebSocket connection open"
ws.send "Hello Client, you connected to: #{Socket.gethostname}. websocket server path: #{handshake.path}"
timer = EventMachine::PeriodicTimer.new(0.5) do
value = (rand(100..6000) / 1000.0 )
message = "time: #{Time.now} value: #{value.to_s}"
ws.send message
puts message
end
}
ws.onclose { puts "Connection closed" }
#ws.onmessage { |msg|
# puts "Received message: #{msg}"
# ws.send "Pong: #{msg}"
#}
end
}
我的逻辑是在尽可能短的持续时间内运行事件机,并为所需的随机值添加延迟。例如
'ws.onopen { |handshake|
puts "WebSocket connection open"
ws.send "Hello Client, you connected to: #{Socket.gethostname}. websocket server path: #{handshake.path}"
timer = EventMachine::PeriodicTimer.new(0.0) do #the delay is kept to minimum here
value = (rand(100..6000) / 1000.0 )
message = "time: #{Time.now} value: #{value.to_s}"
ws.send message
puts message
delay(2) #2 seconds delay or the dynamic delay you want
end
}`
上下文:自行尝试