服务端:
import socketserver class MyServer(socketserver.BaseRequestHandler): def handle(self): #在这个函数里面编写发送和接收的语句 while True: msg = self.request.recv(1024).decode('utf-8') if msg == 'q': break print(msg) info = input('>>>') self.request.send(info.encode('utf-8')) if __name__ == '__main__': server = socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyServer) #设置服务器地址和端口号 server.serve_forever() #持续与客户端通信
客户端1:
import socket sk = socket.socket() sk.connect(('127.0.0.1',8080)) while True: msg = input('>>>') if msg == 'q': sk.send(b'q') break sk.send(('王佃超:{}'.format(msg)).encode('utf-8')) ret = sk.recv(1024).decode('utf-8') print(ret) sk.close()
客户端2:
import socket sk = socket.socket() sk.connect(('127.0.0.1',8080)) while True: msg = input('>>>') if msg == 'q': sk.send(b'q') break sk.send(('尹洪飞:{}'.format(msg)).encode('utf-8')) ret = sk.recv(1024).decode('utf-8') print(ret) sk.close()