You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
2.3 KiB
Python

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import socket
import threading
import time
class TcpServer(object):
def __init__(self):
# 配置信息
self.tcpPort = 12345 # 服务端TCP监听端口
self.udpPort = 54321 # 设备发现UDP端口
self.broadcastAddr = '<broadcast>' # 广播地址
# TCP服务端主逻辑
def tcpServer(self):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('0.0.0.0', self.tcpPort))
server.listen(5)
print(f"[*] TCP服务端已启动监听端口 {self.tcpPort}")
while True:
clientSock, addr = server.accept()
print(f"[+] 接收到来自 {addr} 的连接")
# 创建线程处理客户端请求
client_thread = threading.Thread(target=self.handleClient, args=(clientSock,))
client_thread.start()
# 处理客户端请求
def handleClient(self, clientSock):
try:
while True:
data = clientSock.recv(1024)
if not data:
break
print(f"收到消息: {data.decode('utf-8')}")
clientSock.send(b"ACK") # 返回确认
except Exception as e:
print(f"客户端异常断开: {e}")
finally:
clientSock.close()
# UDP设备发现服务
def udpDiscoveryServer(self):
udpSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udpSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
udpSock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
udpSock.bind(('', self.udpPort))
print(f"[*] UDP发现服务已启动监听端口 {self.udpPort}")
while True:
data, addr = udpSock.recvfrom(1024)
if data.decode('utf-8') == "DISCOVERY_REQUEST":
print(f"[+] 收到来自 {addr} 的发现请求")
response = f"DISCOVERY_RESPONSE:{socket.gethostname()}:{self.tcpPort}"
udpSock.sendto(response.encode('utf-8'), addr)
if __name__ == '__main__':
server = TcpServer()
# 启动TCP服务端和UDP发现服务
threading.Thread(target=server.tcpServer, daemon=True).start()
threading.Thread(target=server.udpDiscoveryServer, daemon=True).start()
# 防止主线程退出
while True:
time.sleep(1)