首页 > 解决方案 > Asyncio/Websocket:客户端不向服务器发送消息

问题描述

我目前正在编写我正在编写一些 Connect 4 软件的课程代码。我已经达到了允许用户跨本地网络玩的项目的一部分。使用 asyncio 和 websocket,我正在使用服务器类和客户端类。服务器读取所有传入消息并将它们转发给每个连接的客户端,客户端从服务器接收和发送消息。

我已经能够让一些客户端进行通信,但由于没有发送客户端消息之一,因此我无法在客户端之间设置游戏。我在代码中添加了两条打印语句,一条添加到服务器类以打印所有收到的消息,一条添加到 ui 代码以确认客户端到达代码中发送消息的位置。

由于这些打印语句,我发现客户端确实到达了代码的那部分,但服务器从未收到消息。

这是应该发送消息的代码:

elif cmd == "tJoin" and message.get("to", None) == self._name and self._hosting and not self._opponent:
    # if there is a join command check if it is directed to this client
    # ask if the client wants to accept the match
    accepted = await ainput(f'Accept match from {message.get("from", None)}? [y|n]\n')
    # if the match is accepted set opponent to the sender and send an acknowledgment to the opponent
    if accepted == "y":
        # let the joiner know the match has been accepted
        print("TEST: CLIENT REACH ERROR POINT")
        # message which is not sending
        await self._client.send({"from": self._name, "to": message.get("from", None), "cmd": "acc"})
        self._opponent = message.get("from", None)
    else:
        await self._client.send({"to": message.get("from", None), "from": self._name, "cmd": "rej"})

其他客户端发送消息都发送到服务器,但接受消息不是。

我已经链接了服务器终端托管客户的终端加入客户的终端

为什么没有发送接受消息?

标签: pythonwebsocketpython-asyncio

解决方案


推荐阅读