版權聲明:轉載請注明作者(獨孤尚良dugushangliang)出處:https://blog.csdn.net/dugushangliang/article/details/100971395
?
參閱:https://websockets.readthedocs.io/en/stable/
先啟動服務端:
import asyncio
import websockets
port=8765
host='localhost'
print(f'ws://{host}:{port}')
async def deal(websocket,path):
message=await websocket.recv()
print(message)
start_server = websockets.serve(deal, host, port)
#下面這行代碼執行后創建一個WebSocket對象
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
啟動服務端后,將一直等待客戶端的連接。
再執行客戶端:
import asyncio
import websockets
async def hello():
uri = "ws://localhost:8765"
async with websockets.connect(uri) as websocket:
message=input('cin: ')
print(f"< {message}")
await websocket.send(message)
#下面代碼一執行,客戶端將和服務端建立連接。客戶端將等待輸入內容,輸入后客戶端即發送此內容到服務端
asyncio.get_event_loop().run_until_complete(hello())
上文的這個代碼,決定了:客戶端連接后只能發送消息并不能接收消息。客戶端發送消息給服務端后,連接即停止。除非再次執行客戶端的最后一行代碼,重新建立連接。
那么,怎么實現,客戶端能一直給服務端發送消息呢?
上loop
async def hello():
uri = "ws://localhost:8765"
async with websockets.connect(uri) as websocket:
while True:
message=input('cin: ')
if message=='esc':
break
print(f"< {message}")
await websocket.send(message)
但有個問題:客戶端發送一條消息后,雖然可以繼續輸入,但是服務端并不接收內容了。這是因為代碼決定了服務端只接收一次。
那么怎么寫代碼,可以讓服務端一直接收消息?
async def deal(websocket,path):
while True:
message=await websocket.recv()
print(message)
還有一種操作:?
async def deal(websocket,path):
async for message in websocket:
message=await websocket.recv()
print(message)
?
?
獨孤尚良dugushangliang——著
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
