1

sinatra-websocket gemを使用して異なるチャネルでメッセージを送信する方法はありますか?

基本的に、Pusher を sinatra-websocket に置き換えようとしています。プッシャーで私がやっていることは次のとおりです。

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

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

このsinatra-websocketスニペットの構文に相当するものは何ですか?

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 
4

1 に答える 1

1

ここに投稿されたこれに対する回答が見つかりました:

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 を通じてこれらすべてを抽象化していると思います。

于 2013-10-26T05:23:15.143 に答える