事件机器websocket服务器:如何将定期消息推送到客户端?

时间:2013-08-22 13:53:24

标签: ruby-on-rails ruby websocket eventmachine

我想使用ruby language 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 msecs(随机值)的某些数据推送到连接的客户端......实际上类似于:

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()系统调用, 但我无法弄清楚如何在EM::WebSocket loop中插入一个周期性事件; 也许与EventMachine::PeriodicTimer?怎么样?

有人可以帮我一个代码示例chunck吗? 谢谢! 乔治

2 个答案:

答案 0 :(得分:3)

我自己找到了一个解决方案:在下面的代码中,服务器每500毫秒将一个websocket消息推送到客户端。 (PeriodicTimer.new(0.5))。

我现在遇到的问题是,如何动态重置计时​​器,每N个msecs发送一条消息,其中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
}

答案 1 :(得分:-1)

我的逻辑是在最短的时间内运行事件机器,并为您需要的随机值添加延迟。例如

'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
}`

背景:自我尝试