2
我正在学习如何将websockets
程序包用于Python 3.6和asyncio
。Python网络套接字:无限锁定客户端recv
使用Websockets Getting Started例如,这里是我的服务器和客户端代码
import asyncio
import websockets
msg_queue = asyncio.Queue()
async def consumer_handler(websocket):
global msg_queue
while True:
message = await websocket.recv()
print("Received message {}".format(message))
await msg_queue.put("Hello {}".format(message))
print("Message queued")
async def producer_handler(websocket):
global msg_queue
while True:
print("Waiting for message in queue")
message = await msg_queue.get()
print("Poped message {}".format(message))
websocket.send(message)
print("Message '{}' sent".format(message))
async def handler(websocket, path):
print("Got a new connection...")
consumer_task = asyncio.ensure_future(consumer_handler(websocket))
producer_task = asyncio.ensure_future(producer_handler(websocket))
done, pending = await asyncio.wait([consumer_task, producer_task]
, return_when=asyncio.FIRST_COMPLETED)
print("Connection closed, canceling pending tasks")
for task in pending:
task.cancel()
start_server = websockets.serve(handler, 'localhost', 5555)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
wsclient.py
wsserver.py(使用python <script>
两个独立的控制台都运行)
import asyncio
import websockets
async def repl():
async with websockets.connect('ws://localhost:5555') as websocket:
while True:
name = input("\nWhat's your name? ")
await websocket.send(name)
print("Message sent! Waiting for server answer")
greeting = await websocket.recv()
# never goes here
print("> {}".format(greeting))
asyncio.get_event_loop().run_until_complete(repl())
执行期间,服务器正在做的是对他的期望:
- 等待客户端的消息
- 队列
'Hello $message'
- 出列它
- 发送出队的消息发回给发送者
客户端确实正在等待服务器响应:
- 等待用户输入
- 它发送到服务器
- 等待答案从服务器< - 持有无限
- 打印&环
这里是控制台输出执行:
服务器
Got a new connection...
Waiting for message in queue
Received message TestName
Message queued
Poped message Hello TestName
Message 'Hello TestName' sent
Waiting for message in queue
客户
What's your name? TestName
Message sent! Waiting for server answer
_
我缺少什么?
后重新读取文档实例和[API规范(https://开头websockets.readthedocs.io/en/stable/api.html#websockets.protocol.WebSocketCommonProtocol.send),我注意到'send'函数是一个协程。谢谢! – aaaaaaa