日志部分参考:https://www.cnblogs.com/singebogo/articles/15722262.html
import socket import threading from log import Logger log = Logger('log//all.log',level='debug') # 多线程服务器 def handle_conn(log, sock, address): log.logger.info("deal with connection ....") t = threading.Thread(target=process_conn, args=(sock, address))#为每个链接创建一个线程,回调函数process_conn t.start() def process_conn(sock, address): print(threading.current_thread()) data = "hello " + str(address) sock.send(data.encode("utf-8")) while True: # 多次为一个客户端服务 try: recv_data = sock.recv(1024).decode("gbk",'ignore') # 如果 recv 解堵塞,客户端有两种方式 1. 发送了数据 2. 关闭了连接 if recv_data: log.logger.info(recv_data) except Exception: print("close socket..") sock.close() break def main(ip="127.0.0.1", port=50007): # 1. create socket tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 2. bind local information tcp_server_socket.bind((ip, port)) # 3. tcp_server_socket.listen() # 4. accept connection from client # 元组解包 while True: print(threading.current_thread()) print("waitting for client ........") new_client_socket, client_addr = tcp_server_socket.accept() handle_conn(log, new_client_socket, client_addr) if __name__ == '__main__': main()