赞
踩
import socket import time HOST = 'localhost' PORT = 12345 BACKLOG = 5 BUFSIZE = 1024 RECONN_DELAY = 1 # 断线重连的延迟时间,单位为秒 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((HOST, PORT)) s.listen(BACKLOG) inputs = [s] outputs = [] exceptions = [] while inputs: readable, writable, exceptional = select.select(inputs, outputs, exceptions) for s in readable: if s is s: # 监听 Socket 可读,有新的连接请求 try: conn, addr = s.accept() print('连接已建立:', addr) inputs.append(conn) except Exception as e: print('连接失败:', e) exceptions.append(s) # 将出现异常的监听 Socket 添加到异常列表中 s.close() # 关闭监听 Socket continue # 继续监听下一轮连接请求 else: # 已连接 Socket 可读,读取数据并处理 try: data = s.recv(BUFSIZE) if not data: # 连接已断开,关闭 Socket 并从 inputs 中移除 print('连接已断开:', s.getpeername()) inputs.remove(s) s.close() continue # 继续监听下一轮连接请求 # 处理数据... except socket.error as e: print('读取数据失败:', e) exceptions.append(s) # 将出现异常的已连接 Socket 添加到异常列表中 s.close() # 关闭已连接 Socket continue # 继续监听下一轮连接请求
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。