python,利用socketserver模块实现并发聊天

利用socketserver模块很容易实现并发功能,下面的server.py和client.py程序实现了这一功能.

#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'))
posted @ 2019-12-14 07:05  Iceberg_710815  阅读(222)  评论(0编辑  收藏  举报