gpt4 book ai didi

python - 运行 python websocket 库示例代码时出错

转载 作者:太空宇宙 更新时间:2023-11-03 21:42:53 25 4
gpt4 key购买 nike

我提供的示例代码有错误,我在谷歌上没有找到任何内容,这是回溯

ERROR:websockets.server:Error in connection handler
Traceback (most recent call last):
File "C:\Users\felix\AppData\Local\Programs\Python\Python36\lib\site-packages\websockets\server.py", line 84, in handler
yield from self.ws_handler(self, path)
File "C:\Users\felix\Desktop\letistry\server.py", line 45, in counter
async for message in websocket:
TypeError: 'async for' requires an object with __aiter__ method, got WebSocketServerProtocol

我所做的就是从 https://websockets.readthedocs.io/en/stable/intro.html 复制并粘贴代码

我在 Windows 10 上的 python 3.6 上运行同步示例(代码如下)。

#!/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)

asyncio.get_event_loop().run_until_complete(
websockets.serve(counter, 'localhost', 6789))
asyncio.get_event_loop().run_forever()

最佳答案

根据此线程,这似乎是依赖库 telethon 中的错误:

https://github.com/expectocode/telegram-export/issues/33

例如,如果您使用发行版附带的过时软件包,则可能会发生这种情况。使用 virtualenv 并确保我在虚拟环境中通过 pip 使用最新的软件包解决了我的问题。

具体来说,Ubuntu 18.04 上使用 python3-websockets 包安装的版本当前为 3.4-1。在虚拟环境中使用pip,版本为8.0.3。

关于python - 运行 python websocket 库示例代码时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52712175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com