服务端代码
#引入socketserver模块 import socketserver #定义处理类必须继承BaseRequestHandler类 class my_server(socketserver.BaseRequestHandler): def handle(self): #获取连接 print(self.request) #conn #获取地址 print(self.client_address)#addr while True: try: # 收消息 data=self.request.recv(1024) #可能会出现不断的收 if not data:break #self.request:连接信息 self.client_address:链接地址 print("a client is connented", self.request, ":", self.client_address) print("收到客户端消息是:",data.decode("utf-8")) #发消息 self.request.sendall(data) except Exception as e: print(e) break if __name__=='__main__': print("This server is started") #多线程 s=socketserver.ThreadingTCPServer(('127.0.0.1',8080) ,my_server) #永远服务 s.serve_forever()
客户端代码
from socket import * ip_port=("127.0.0.1",8080) buffer_size=1024 #客户端 tcp_client=socket(AF_INET,SOCK_STREAM) #连接服务端 tcp_client.connect(ip_port) while True: msg=input("===>:") tcp_client.send(msg.encode("utf- 8")) data=tcp_client.recv(buffer_size) print("收到的服务端消息为:",data.decode("utf-8")) tcp_client.close