Rails ActionCable是否丢失数据包?

问题描述

我想制作一个RPG浏览器游戏只是为了好玩,所以我创建了一个简单的频道来测试多客户端服务器的工作方式。

功能

  • 我使用模型来了解玩家是否开/关。
  • 开启新播放器时(http:// localhost:3000 / rpg) 向他发送他的ID和在线人数。

我只是打开了几个标签,乍一看效果很好。

错误

  1. 有时登录时服务器发送玩家ID,但客户端发送 没有收到,我刷新页面,直到出现此错误
  2. 有时客户端会保持登录状态,如果不调用RpgChannel#unsubscribed,我不知道如何重现此错误,我认为ActionCable会出现超时或某些错误

我不知道这是否是在Rails中制作RPG浏览器游戏的最佳方法,但这是我认为的唯一方法我只是丢包了,这很正常吗?

我从一个简单的模型开始:

rails g model Player connected:boolean

然后进行简单查看:

app / views / welcome / rpg.html.erb

ID: <span class="player_id"></span>
<br>
Players Online: <span class="players_online"></span>

这是我的频道:

app / channels / rpg_channel.rb

class RpgChannel < ApplicationCable::Channel
    def subscribed
        if self.current_player
            # Sending Player ID to current player.
            stream_for self.current_player
            RpgChannel.broadcast_to(self.current_player,{id: self.current_player.id})

            # Sending Players Online to everybody.
            stream_from "RpgChannel"
            ActionCable.server.broadcast("RpgChannel",{players_online: Player.where(connected: true).size})
        end
    end

    def unsubscribed
        if self.current_player
            self.current_player.update(connected: false)
            ActionCable.server.broadcast("RpgChannel",{players_online: Player.where(connected: true).size})
        end
    end
end

应用/资产/javascript/channels/rpg.coffee

App.rpg = App.cable.subscriptions.create "RpgChannel",connected: ->
    # Called when the subscription is ready for use on the server
    console.log "CONNECTED"

  disconnected: ->
    # Called when the subscription has been terminated by the server
    console.log "disCONNECTED"
    $(".player_id").text("disCONNECTED")
    $(".players_online").text("disCONNECTED")

  received: (data) ->
    # Called when there's incoming data on the websocket for this channel
    console.log data
    if "id" of data
        $(".player_id").text("#{data["id"]}")
    if "players_online" of data
        $(".players_online").text("#{data["players_online"]}")

app / channels / application_cable / connection.rb

module ApplicationCable
    class Connection < ActionCable::Connection::Base
        identified_by :current_player
        
        def connect
            self.current_player = find_player
        end
        
        protected
        def find_player
            player = Player.find_by(connected: false)
            if player
                player.update(connected: true)
                return player
            else
                return Player.create(connected: true)
            end
        end
    end
end

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...