socket编程-多个客户端向服务器发送数据(服务器使用多线程)
服务器端:
import socket import threading class recogServer: def __init__(self): print('启动服务') self.sock = socket.socket() #创建socket self.addr = ('127.0.0.1',9999) #服务器要绑定的IP和端口 self.sock.bind(self.addr) #绑定IP和端口 有一个端口已占用的问题 self.clients = {} def start(self): self.sock.listen() accept_thread = threading.Thread(target=self.accept, name='accpet_thread') accept_thread.start() def accept(self): while True: s, raddr = self.sock.accept() self.clients[raddr] = s recv_thread = threading.Thread(target=self.recv, name='recv_thread', args=(s, raddr)) recv_thread.start() def recv(self, s, raddr): while True: try: data = s.recv(1024) s.send(b'ack') print('host('+ raddr[0]+':'+str(raddr[1]) + '):'+data.decode()) if data.decode() == 'quit': s.close() break except ConnectionResetError: print('The remote host:('+ raddr[0]+':'+str(raddr[1]) + ') closed') s.close() break def stop(self): for item in self.clients.values(): item.close() self.sock.close() if __name__ == '__main__': myserver = recogServer() myserver.start() while True: input_str = input('>>>') if input_str.strip() == 'quit': myserver.stop() break print(threading.enumerate())
客户端:
import socket import threading def Fun(addr): sock = socket.socket() sock.connect(addr) while True: mystr = input('Input sending data: ') try: sock.send(mystr.encode()) data = sock.recv(1024) print('server reply:'+data.decode()) if mystr == 'quit' and data.decode() == 'ack': sock.close() break except ConnectionResetError: print('服务器端故障') sock.close() break if __name__ == '__main__': addr = ('127.0.0.1', 9999) Fun(addr)