python 网络通讯 服务器端代码demo,能够同时处理多个客户端的连接请求
这是一个python网络通讯服务器端的代码demo,能够同时处理多个客户端的连接请求。
from socket import * import threading from datetime import * import time import signal server=socket(AF_INET,SOCK_STREAM) server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) server.bind(("",4000)) server.listen(10) print('waiting to connecting from clients') def client_thread(client_socket,client): global connect_count global is_exit while not is_exit: data=client_socket.recv(1024) # when return value is b'',the connect with client is close if data !=b'': print(str(datetime.now()),' ',client[0],':',data) client_socket.send(bytes('数据接收成功!', encoding = "utf8") ) if data=="over" or data ==b'': if mutex_num.acquire(1): connect_count=connect_count-1 print("client",client[0],"shutdown,current connect count is",connect_count) mutex_num.release() client_socket.close() break def handle(signum, frame): global is_exit is_exit = True print("receive a signal {0},is_exit={1}").format(signum, is_exit) signal.signal(signal.SIGINT, handle) signal.signal(signal.SIGTERM, handle) mutex_num = threading.Lock() connect_count = 0 max_connect_num = 10 is_exit = False thread_set = [] while not is_exit: client_socket, client = server.accept() if mutex_num.acquire(1): connect_count = connect_count + 1 print("receive new connect from:", client, "current connect count :", connect_count) mutex_num.release() t = threading.Thread(target=client_thread, args=(client_socket, client)) t.setDaemon(True) t.start() thread_set.append(t) while (1): isalive = False for t in thread_set: flag = t.is_alive() isalive = isalive or flag if not isalive: break server.close()