websocket 代码实现
import asyncio
import websockets
websocket_users = {}
async def recv_user_msg(websocket):
recv_text = await websocket.recv()
print("recv_text:", websocket.pong, recv_text)
text = recv_text.split(':')
if text[0] not in websocket_users:
websocket_users[text[0]] = websocket
print(websocket_users)
else:
response_text = f"{text[0]}: {text[1]}"
print(websocket_users)
for i, r in websocket_users.items():
if i != text[0]:
await r.send(response_text)
async def run(websocket, path):
while True:
try:
await recv_user_msg(websocket)
except websockets.ConnectionClosed:
print("ConnectionClosed...", path)
print("websocket_users old:", websocket_users)
for k in websocket_users.copy():
if websocket_users[k] == websocket:
websocket_users.pop(websocket)
print("websocket_users new:", websocket_users)
break
except websockets.InvalidState:
print("InvalidState...")
break
except Exception as e:
print("Exception:", e)
if __name__ == '__main__':
print("127.0.0.1:8181 websocket...")
asyncio.get_event_loop().run_until_complete(websockets.serve(run, "127.0.0.1", 8181))
asyncio.get_event_loop().run_forever()
import asyncio
import websockets
async def hello():
uri = "ws://localhost:8181"
async with websockets.connect(uri) as websocket:
name = input("What's your name? ")
await websocket.send(name)
print(f"> {name}")
greeting = await websocket.recv()
print(f"< {greeting}")
asyncio.get_event_loop().run_until_complete(hello())
困惑点:ping/pong是何时发送的,在停止发消息后主动推送pingpon?
|