import socket
import threading
# 定义服务器的主机和端口
HOST = '0.0.0.0'
PORT = 12345
# 存储所有客户端连接
clients = []
def handle_client(client_socket, client_address):
print(f"新连接: {client_address}")
try:
while True:
# 接收客户端发送的数据
data = client_socket.recv(1024).decode('utf-8')
if not data:
break
print(f"收到来自 {client_address} 的消息: {data}")
# 这里可以添加处理控制指令的逻辑
if data == 'start':
print("启动 3D 全息展示柜")
elif data == 'stop':
print("停止 3D 全息展示柜")
# 向所有客户端广播消息
for client in clients:
if client != client_socket:
client.sendall(f"{client_address} 发送了: {data}".encode('utf-8'))
except Exception as e:
print(f"处理客户端 {client_address} 时出错: {e}")
finally:
# 关闭客户端连接并从列表中移除
clients.remove(client_socket)
client_socket.close()
print(f"连接关闭: {client_address}")
def start_server():
# 创建 TCP 套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定主机和端口
server_socket.bind((HOST, PORT))
# 开始监听连接
server_socket.listen()
print(f"服务器正在监听 {HOST}:{PORT}")
try:
while True:
# 接受新的连接
client_socket, client_address = server_socket.accept()
clients.append(client_socket)
# 为每个客户端创建一个新线程来处理
client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
client_thread.start()
except KeyboardInterrupt:
print("服务器关闭")
finally:
# 关闭所有客户端连接和服务器套接字
for client in clients:
client.close()
server_socket.close()
if __name__ == "__main__":
start_server()

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69996424/viewspace-3078610/ ,如需转载,请注明出处,否则将追究法律责任。