1、基于TCP协议:
服务端:
1 import socketserver 2 3 class MyHandler(socketserver.BaseRequestHandler): 4 def handle(self): 5 #通信循环 6 while True: 7 # print(self.client_address) 8 # print(self.request) #self.request=conn 9 10 try: 11 data=self.request.recv(1024) 12 if len(data) == 0:break 13 self.request.send(data.upper()) 14 except ConnectionResetError: 15 break 16 17 18 if __name__ == '__main__': 19 s=socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyHandler,bind_and_activate=True) 20 21 s.serve_forever() # 代表连接循环 22 # 循环建立连接,每建立一个连接就会启动一个线程(服务员)+调用Myhanlder类产生一个对象,调用该对象下的handle方法,专门与刚刚建立好的连接做通信循环
客户端:
1 import socket 2 3 phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) 4 phone.connect(('127.0.0.1',8080)) # 指定服务端ip和端口 5 6 while True: 7 # msg=input('>>: ').strip() #msg='' 8 msg = 'client33333' # msg='' 9 if len(msg) == 0:continue 10 phone.send(msg.encode('utf-8')) 11 data=phone.recv(1024) 12 print(data) 13 14 15 phone.close()
2、基于UDP协议:
服务端:
1 import socketserver 2 3 class MyHandler(socketserver.BaseRequestHandler): 4 def handle(self): 5 #通信循环 6 # print(self.client_address) 7 # print(self.request) 8 9 data=self.request[0] 10 print('客户消息',data) 11 self.request[1].sendto(data.upper(),self.client_address) 12 13 14 if __name__ == '__main__': 15 s=socketserver.ThreadingUDPServer(('127.0.0.1',8080),MyHandler) 16 s.serve_forever()
客户端:
1 import socket 2 3 client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #数据报协议-》udp 4 5 while True: 6 # msg=input('>>: ').strip() #msg='' 7 msg='client444444' 8 9 client.sendto(msg.encode('utf-8'),('127.0.0.1',8080)) 10 data,server_addr=client.recvfrom(1024) 11 print(data) 12 13 client.close()