我提供的示例代码有错误,我在google上没有找到任何内容,这是回溯
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复制和粘贴代码
im在Windows 10的python 3.6上运行Synchronization示例(代码如下)。
#!/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()
答案 0 :(得分:0)
根据此线程,这似乎是依赖性库telethon
中的错误:
https://github.com/expectocode/telegram-export/issues/33
例如,如果您使用的是发行版随附的过时软件包,则可能会发生这种情况。使用virtualenv
并确保我在虚拟环境中通过pip
使用了最新的软件包,为我解决了这个问题。
具体来说,在Ubuntu 18.04上与软件包python3-websockets
一起安装的版本当前为3.4-1。在虚拟环境中使用pip
,版本是8.0.3。