Repository navigation
Expand file tree
/
Copy pathtest_server.py
More file actions
56 lines (48 loc) · 1.81 KB
/
Copy pathtest_server.py
File metadata and controls
56 lines (48 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import asyncio
import websockets
import socket
import json
import time
connected_clients = set()
async def handler(websocket, path=None):
connected_clients.add(websocket)
print(f">>> [连接成功] 有新设备加入。当前在线设备数: {len(connected_clients)}")
try:
# 增加时间戳,确保手机端解析成功
welcome = json.dumps({
"senderId": "System",
"content": "已成功接入局域网中转服务器",
"timestamp": int(time.time() * 1000)
})
await websocket.send(welcome)
async for message in websocket:
print(f"收到消息并智能广播: {message}")
if connected_clients:
# 修复发送两遍的问题:广播时排除当前发送者 (websocket)
targets = [client for client in connected_clients if client != websocket]
if targets:
tasks = [client.send(message) for client in targets]
await asyncio.gather(*tasks, return_exceptions=True)
except websockets.exceptions.ConnectionClosed:
print("设备断开连接")
finally:
connected_clients.remove(websocket)
def get_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
return ip
except:
return "127.0.0.1"
async def main():
ip = get_ip()
print(f"=== 局域网广播服务器 (已修复回显与时间戳) ===")
print(f"1. 你的电脑 IP: {ip}")
print(f"2. 端口: 12345")
print(f"===========================================")
async with websockets.serve(handler, "0.0.0.0", 12345):
await asyncio.Future()
if __name__ == "__main__":
asyncio.run(main())