websocket服务端和客户端初始版
This commit is contained in:
commit
811de8d76f
50
webSocketClient.py
Normal file
50
webSocketClient.py
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
import websockets
|
||||||
|
import asyncio
|
||||||
|
from aioconsole import ainput # 使用异步输入库
|
||||||
|
|
||||||
|
class WebSocketClient:
|
||||||
|
def __init__(self, url):
|
||||||
|
self.url = url
|
||||||
|
|
||||||
|
async def run(self):
|
||||||
|
try:
|
||||||
|
async with websockets.connect(self.url) as websocket:
|
||||||
|
print("Connected to server.")
|
||||||
|
sender = asyncio.create_task(self.send_messages(websocket))
|
||||||
|
receiver = asyncio.create_task(self.receive_messages(websocket))
|
||||||
|
await asyncio.gather(sender, receiver)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error: {e}")
|
||||||
|
|
||||||
|
async def send_messages(self, websocket):
|
||||||
|
"""使用异步输入处理用户输入"""
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
# 使用aioconsole的异步输入避免阻塞
|
||||||
|
message = await ainput("Enter message (or 'exit' to quit): ")
|
||||||
|
if message.lower() == "exit":
|
||||||
|
await websocket.close()
|
||||||
|
break
|
||||||
|
await websocket.send(message)
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass # 任务被取消时正常退出
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Send error: {e}")
|
||||||
|
|
||||||
|
async def receive_messages(self, websocket):
|
||||||
|
"""优化消息显示格式"""
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
message = await websocket.recv()
|
||||||
|
# 使用ANSI转义码清除当前行并打印服务器消息
|
||||||
|
print(f"\r\033[K[Server] {message}", flush=True)
|
||||||
|
# 重新显示输入提示
|
||||||
|
print("Enter message (or 'exit' to quit): ", end="", flush=True)
|
||||||
|
except websockets.exceptions.ConnectionClosed:
|
||||||
|
print("\nConnection closed.")
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass # 任务被取消时正常退出
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
client = WebSocketClient("ws://10.0.0.202:8788")
|
||||||
|
asyncio.run(client.run())
|
||||||
20
webSocketServer_0.py
Normal file
20
webSocketServer_0.py
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
import websockets
|
||||||
|
import asyncio
|
||||||
|
import time
|
||||||
|
|
||||||
|
async def echo_server(websocket):
|
||||||
|
print("Client connected.")
|
||||||
|
try:
|
||||||
|
async for message in websocket:
|
||||||
|
print(f"Received: {message}")
|
||||||
|
response = f"Echo: {message}"
|
||||||
|
await websocket.send(response)
|
||||||
|
except websockets.exceptions.ConnectionClosed:
|
||||||
|
print("Client disconnected.")
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
async with websockets.serve(echo_server, "10.0.0.202", 8788):
|
||||||
|
await asyncio.Future() # 永久运行
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
50
webSocketServer_1.py
Normal file
50
webSocketServer_1.py
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
'''
|
||||||
|
服务端定时向客户端发送消息
|
||||||
|
'''
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import websockets
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
# 存储所有连接的客户端
|
||||||
|
connected_clients = set()
|
||||||
|
|
||||||
|
async def send_periodic_messages(interval=5):
|
||||||
|
"""定期向所有客户端发送消息"""
|
||||||
|
while True:
|
||||||
|
await asyncio.sleep(interval)
|
||||||
|
if connected_clients:
|
||||||
|
# message = "{'socketType':'7','number':'ROB23100098','groupingId':'0dc1ad7fdb394246981b8576465240ce','onlineStatus':'1','robotId':'6865c4ce61ee45a69e79f62eee55b83c'}"
|
||||||
|
message = "{\"socketType\":\"7\",\"number\":\"ROB23100098\",\"groupingId\":\"0dc1ad7fdb394246981b8576465240ce\",\"onlineStatus\":\"1\",\"robotId\":\"6865c4ce61ee45a69e79f62eee55b83c\"}"
|
||||||
|
# 6865c4ce61ee45a69e79f62eee55b83c
|
||||||
|
# 向所有客户端广播消息
|
||||||
|
await asyncio.wait([client.send(message) for client in connected_clients])
|
||||||
|
|
||||||
|
async def handle_client(websocket, path):
|
||||||
|
"""处理客户端连接"""
|
||||||
|
# 添加新客户端
|
||||||
|
connected_clients.add(websocket)
|
||||||
|
try:
|
||||||
|
# 保持连接开放
|
||||||
|
async for message in websocket:
|
||||||
|
# 可选的:处理客户端发来的消息
|
||||||
|
print(f"Received: {message}")
|
||||||
|
finally:
|
||||||
|
# 客户端断开时移除
|
||||||
|
connected_clients.remove(websocket)
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
# 启动定时任务
|
||||||
|
asyncio.create_task(send_periodic_messages(interval=10))
|
||||||
|
|
||||||
|
# 启动WebSocket服务器
|
||||||
|
server = await websockets.serve(
|
||||||
|
handle_client,
|
||||||
|
"10.0.0.202",
|
||||||
|
8788
|
||||||
|
)
|
||||||
|
print("WebSocket server started on ws://10.0.0.202:8788")
|
||||||
|
await server.wait_closed()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(main())
|
||||||
Loading…
Reference in New Issue
Block a user