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