python,应用socketserver模块实现并发聊天程序
server.py import socketserver class MyServer(socketserver.BaseRequestHandler): def handle(self): while True: conn = self.request while True: data = conn.recv(1024) if str(data,'utf8') == 'q': break print(str(data,'utf8')) inp = input('>>>') conn.send(bytes(inp,'utf8')) conn.close() if __name__ == '__main__': server = socketserver.ThreadingTCPServer(('127.0.0.1',8000),MyServer) server.serve_forever()
client.py import socket sk = socket.socket() address = ('127.0.0.1',8000) sk.connect(address) while True: inp = input('>>>') if inp == 'q': print('Bye-bye') break sk.send(bytes(inp,'utf8')) data = sk.recv(1024) print(str(data,'utf8'))
解析:server.py首先调用了socketserver模块,建立一个自己的类MyServer并继承了socketserver.BaseRequestHandler,重写该类的hander方法,server = socketserver.ThreadingTCPServer(('127.0.0.1',8000),MyServer)命令实现了对IP地址,端口和协议的封装,将用户自己要实现的并发聊天代码写进handle方法,程序执行的时候就是到handle方法中去找代码执行.从而实现了并发聊天.