版权声明:转载请注明作者(独孤尚良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——著