小编phy*_*cus的帖子

使用 websocket 的 Python 多人游戏:处理多个客户端

我正在尝试通过websockets在 Python 中构建多人游戏(准确地说是纸牌游戏),但目前我在早期步骤中失败了。

我正在尝试做的事情:

  • 客户端连接到 websocket,直到达到一定数量
  • 客户端向服务器发送输入
  • 服务器分别并同时响应每个客户端

什么有效:

  • 让客户端连接并为每个客户端存储一个 websocket 按预期工作,但我有点卡住了。

我尝试过的:

客户端.py

import asyncio
import websockets
import random


def random_name():
    return "".join([random.choice("abcdefghijkl") for _ in range(5)])


async def main():
    uri = "ws://localhost:1235"
    print("Starting...")
    async with websockets.connect(uri) as ws:
        client_name = random_name()
        await ws.send(client_name)
        print(await ws.recv())  # server sends :client_name registered
        print(await ws.recv())  # server sends: 3 people registered
        print(await ws.recv())  # server sends: Waiting for input
        inp = input()
        await ws.send(inp)

asyncio.get_event_loop().run_until_complete(main())
Run Code Online (Sandbox Code Playgroud)

server.py (非常幼稚的方法)

import websockets
import …
Run Code Online (Sandbox Code Playgroud)

python asynchronous multiplayer websocket async-await

7
推荐指数
0
解决办法
4456
查看次数