我正在尝试使用画布上的vanilla-js和websocket的Django-Channels构建一款多人,快节奏,侧滚动的平台游戏,称为Star Jumper。我无法通过服务器获取足够的消息以使延迟可播放。发送到服务器的消息包括按下/向上键,鼠标单击和定期对帐。为了解决问题,我只关注定期对帐,在consumers.py中的redis服务器上设置了两个计数器。py-(1)从客户端收到的对帐和(2)发送到相对客户端的对帐。在游戏中有2个玩家的情况下,服务器的已收到消息计数器开始以每秒10个左右的速度(超过2个玩家,每秒总共20个)超过发送的消息计数器。我希望我做错了什么,Django Channels每秒可以处理20条以上的消息,但我很困惑。
下面的相关代码repo is here很高兴澄清/发布更多。在仓库中,“ multiplayer.html”模板具有我的动画循环和套接字流量管理。
在“ StarJumper / templates / multiplayer.html”中
let socket = new ReconnectingWebSocket(ws_path)
function Reconcile() {
socket.send(JSON.stringify({
"command": "reconcile",
"game": {{ game.id }},
"client_now": global_now,
"current": {
"x_pos": world.player.x_pos,
"y_pos": world.player.y_pos,
"vy": world.player.vy,
"color": world.player.color,
}
}))
}
在“ StarJumper / app / consumers.py”中...
async def receive_json(self, content):
game = await get_game_or_error(content["game"], self.scope["user"])
command = content.get("command", None)
if command == "join":
await self.join_game(content)
elif command == "reconcile":
msg_ct = cache.get("msg_ct")
cache.set("msg_ct", msg_ct + 1, timeout=CACHE_TTL)
await self.reconcile_group(content)
# other commands stripped out for this post
async def join_game(self, content):
# other join stuff stripped out for post
cache.set("msg_ct", 0, timeout=CACHE_TTL)
cache.set("thru_ct", 0, timeout=CACHE_TTL)
cache.set(game.group_name + "." + self.scope["user"].username + ".client_now", 0, timeout=CACHE_TTL)
async def reconcile_group(self, content):
game = await get_game_or_error(content["game"], self.scope["user"])
if cache.get(game.group_name + "." + self.scope["user"].username + ".client_now") < content["client_now"]:
await self.channel_layer.group_send(
game.group_name,
{
"type": "reconcile.client",
"username": self.scope["user"].username,
"current": content["current"],
"game": game.group_name,
}
)
cache.set(game.group_name + "." + self.scope["user"].username + ".client_now", content["client_now"], timeout=CACHE_TTL)
async def reconcile_client(self, event):
if event["username"] != self.scope["user"].username:
thru_ct = cache.get("thru_ct")
cache.set("thru_ct", thru_ct + 1, timeout=CACHE_TTL)
msg_ct = cache.get("msg_ct")
print(msg_ct, thru_ct, msg_ct - thru_ct)
await self.send_json(
{
"type": "reconcile",
"username": event["username"],
"current": event["current"],
}
)