Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中的websockets库是如何工作的_Python_Sockets_Websocket - Fatal编程技术网

python中的websockets库是如何工作的

python中的websockets库是如何工作的,python,sockets,websocket,Python,Sockets,Websocket,我正在为我的一个项目使用python中的websocket库。它对我有用,但我很想知道它是如何工作的。我在文档中找不到这个。具体来说,对于文档中给出的示例 #!/usr/bin/env python # WS server example that synchronizes state across clients import asyncio import json import logging import websockets logging.basicConfig() STATE

我正在为我的一个项目使用python中的websocket库。它对我有用,但我很想知道它是如何工作的。我在文档中找不到这个。具体来说,对于文档中给出的示例

#!/usr/bin/env python

# WS server example that synchronizes state across clients

import asyncio
import json
import logging
import websockets

logging.basicConfig()

STATE = {"value": 0}

USERS = set()


def state_event():
    return json.dumps({"type": "state", **STATE})


def users_event():
    return json.dumps({"type": "users", "count": len(USERS)})


async def notify_state():
    if USERS:  # asyncio.wait doesn't accept an empty list
        message = state_event()
        await asyncio.wait([user.send(message) for user in USERS])


async def notify_users():
    if USERS:  # asyncio.wait doesn't accept an empty list
        message = users_event()
        await asyncio.wait([user.send(message) for user in USERS])


async def register(websocket):
    USERS.add(websocket)
    await notify_users()


async def unregister(websocket):
    USERS.remove(websocket)
    await notify_users()


async def counter(websocket, path):
    # register(websocket) sends user_event() to websocket
    await register(websocket)
    try:
        await websocket.send(state_event())
        async for message in websocket:
            data = json.loads(message)
            if data["action"] == "minus":
                STATE["value"] -= 1
                await notify_state()
            elif data["action"] == "plus":
                STATE["value"] += 1
                await notify_state()
            else:
                logging.error("unsupported event: {}", data)
    finally:
        await unregister(websocket)


start_server = websockets.serve(counter, "localhost", 6789)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
每当我断开连接时,就会触发事件
unregister()
websocket
如何知道我已断开连接?
我猜websocket中消息的行
async:
与此有关,但我不知道细节。如果您对此有任何了解,我们将不胜感激。

对于WebSocket模块,断开连接将作为例外情况处理。例如,如果要处理不同类型的断开连接,可以执行以下操作:

try:
    await websocket.send(state_event())
        async for message in websocket:
            # Your code...
except websockets.exceptions.ConnectionClosedOK:
    print("Client disconnected OK")
except websockets.exceptions.ConnectionClosedError:
    print("Client disconnected unexpectedly")
finally:
    await unregister(websocket)

更多信息可以在中找到。

对于WebSocket模块,断开连接将作为异常处理。例如,如果要处理不同类型的断开连接,可以执行以下操作:

try:
    await websocket.send(state_event())
        async for message in websocket:
            # Your code...
except websockets.exceptions.ConnectionClosedOK:
    print("Client disconnected OK")
except websockets.exceptions.ConnectionClosedError:
    print("Client disconnected unexpectedly")
finally:
    await unregister(websocket)
有关更多信息,请参阅