2013-06-30 61 views
1

有沒有辦法使用sinatra-websocket gem在不同頻道上發送消息?使用sinatra-websocket在不同頻道上發送消息

基本上我試圖用sinatra-websocket替換Pusher。下面是我在做什麼用推杆:

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

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

什麼會是語法在此西納特拉,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 
+0

打開很多套接字,也許? – akonsu

回答

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來抽象所有這些。