day32-socketserver
#socketserver 是在socket基础上进行了封装,它让server可以实时跟多个client进行通信。 #thread线程:一个程序有一个线程,一个线程是调度cpu的最小单位。程序运行才产生线程,不运行就不产生。 #如果启用多个线程去接收多个client的请求,就能实现并发的效果。 # server: import socketserver class MyServer(socketserver.BaseRequestHandler): #必须继承此父类 def handle(self): #必须定义此函数,self.request相当于conn while True: msg = self.request.recv(1024).decode('utf-8') print(msg) if msg == 'q': break info = input('server:') self.request.send(info.encode('utf-8')) if __name__ == '__main__': server = socketserver.ThreadingTCPServer(('127.0.0.1',8888),MyServer) #实例化对象 = 类() server.serve_forever() #client1: import socket sk = socket.socket() sk.connect(('127.0.0.1',8888)) while True: info = input('client1:') if info == 'q': sk.send(info.encode('utf-8')) break sk.send(info.encode('utf-8')) ret = sk.recv(1024).decode('utf-8') print(ret) sk.close() #client2: import socket sk = socket.socket() sk.connect(('127.0.0.1',8888)) while True: info = input('client2:') if info == 'q': sk.send(info.encode('utf-8')) break sk.send(info.encode('utf-8')) ret = sk.recv(1024).decode('utf-8') print(ret) sk.close()