【问题标题】:Send messages on different channels using sinatra-websocket使用 sinatra-websocket 在不同的通道上发送消息
【发布时间】:2013-06-27 11:37:44
【问题描述】:

有没有办法使用sinatra-websocket gem 在不同的频道上发送消息?

基本上我正在尝试用 sinatra-websocket 替换 Pusher。下面是我对 Pusher 所做的事情:

Pusher["my_channel_A"].trigger('some_event_type', my_message)

Pusher["my_channel_B"].trigger('another_event_type', my_message)

在这个 sinatra-websocket sn-p 中该语法的等价物是什么?

request.websocket do |ws|
  ws.onopen do
    ws.send("Hello World!")
    settings.sockets << ws
  end
  ws.onmessage do |msg|
    EM.next_tick { settings.sockets.each{|s| s.send(msg) } }
  end
  ws.onclose do
    warn("websocket closed")
    settings.sockets.delete(ws)
  end
end 

【问题讨论】:

  • 打开许多套接字,也许?

标签: ruby websocket sinatra em-websocket


【解决方案1】:

找到这个帖子here的答案:

get '/socket/live/game/:id' do 
    if !request.websocket?
        puts "Not a websocket request"
    else
        request.websocket do |ws|
            channel = params[:id]
            @con = {channel: channel, socket: ws}
            ws.onopen do
                ws.send("Hello World!")
                settings.sockets << @con
            end
            ws.onmessage do |msg|
                return_array = []
                settings.sockets.each do |hash|
                    #puts hash
                    #puts hash['channel']
                    if hash[:channel] == channel
                        #puts hash[:socket]
                        return_array << hash
                        puts "Same channel"
                        puts return_array
                    else
                        puts hash[:channel]
                        puts channel
                        puts "Not in same channel"
                    end
                end
                EM.next_tick { return_array.each{|s| s[:socket].send(msg) } }
            end
            ws.onclose do
                warn("websocket closed")
                settings.sockets.each do |hash|
                    if hash[:socket] == ws
                        settings.sockets.delete(hash)
                        puts "deleted"
                    else
                        puts "not deleted"
                    end
                end
            end
        end
    end
end

它仍然很冗长。我猜 Pusher 通过他们的 API 抽象出所有这些。

【讨论】:

    猜你喜欢
    • 2014-11-12
    • 2020-01-07
    • 2019-01-14
    • 2023-03-15
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 2021-04-15
    相关资源
    最近更新 更多