【问题标题】:ActionCable displaying message in multiple channelsActionCable 在多个频道中显示消息
【发布时间】:2017-02-17 16:57:53
【问题描述】:

我正在使用 ActionCable 在我的游戏室(游戏)内实现聊天。 到目前为止,这是我的代码:

app/channels/game_channel.rb:

class GameChannel < ApplicationCable::Channel
  def subscribed
    stream_from "game_channel_#{params[:game]}" 
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end

  def speak (data)
     ActionCable.server.broadcast("game_channel_#{params[:game]}", data) 
  end
end

app/assets/javascripts/channels/game.js.erb:

<% Game.all.each do |game| %>  

  App['game' + <%=game.id%>] = App.cable.subscriptions.create({channel: 'GameChannel', game: <%= game.id %>}, {  
  received: function(data) {
   alert(message)
   },

  setGameId: function(gameId) {
    this.gameId = gameId
  },
  
  speak: function(data) {
    this.perform('speak'), message => data['message']
    }
});
<% end %>

当我发送命令时:

App.game1.speak (message: "Test1", player: 1, game:1)

--> Alerts Msg:"Test1" @ Game 1.

App.game2.speak (message: "Hello", player: 2, game:2) 

--> Alerts Msg "Hello" @ Game 2, AND @ Game 1 它再次提醒 msg: "Test1"

如何解决这个问题,只显示@更新游戏的消息,而不在其他游戏房间更新?

服务器正在显示:

17:03:01 web.1  | GameChannel is transmitting the subscription confirmation
17:03:01 web.1  | GameChannel is streaming from game_channel_2
17:03:01 web.1  | GameChannel is transmitting the subscription confirmation
17:03:01 web.1  | GameChannel is streaming from game_channel_1
17:03:06 web.1  | GameChannel#speak
17:03:06 web.1  | [ActionCable] Broadcasting to game_channel_1: {"action"=>"speak"}
17:03:06 web.1  | GameChannel transmitting {"action"=>"speak"} (via streamed from game_channel_1)
17:03:06 web.1  | GameChannel transmitting {"action"=>"speak"} (via streamed from game_channel_1)
17:03:11 web.1  | GameChannel#speak
17:03:11 web.1  | [ActionCable] Broadcasting to game_channel_2: {"action"=>"speak"}
17:03:11 web.1  | GameChannel transmitting {"action"=>"speak"} (via streamed from game_channel_2)
17:03:11 web.1  | GameChannel transmitting {"action"=>"speak"} (via streamed from game_channel_2)

【问题讨论】:

    标签: ruby-on-rails ruby websocket actioncable


    【解决方案1】:

    这是我的解决方案(我不知道,但似乎不对),任何 cmets? 我在我的 game.js.erb 中添加了以下条件:

    <% Game.all.each do |game| %>  
      App['game' + <%= game.id %>] = App.cable.subscriptions.create({channel: 'GameChannel', game: <%= game.id %>}, {  
      received: function(data) {
      if (game == <%= game.id %>) {
      alert ('message: ' + message + '; game: ' + <%= game.id %> + '; game: ' + game);
          }},
    
      setGameId: function(gameId) {
        this.gameId = gameId
      },
    
      speak: function(data) {
        this.perform('speak')
        }
    });
    <% end %>
    

    基本上我是在比较发送的游戏和游戏室ID。

    【讨论】:

      猜你喜欢
      • 2017-12-12
      • 1970-01-01
      • 2016-09-21
      • 2020-12-12
      • 1970-01-01
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      相关资源
      最近更新 更多