基于tcp协议通信
服务端必须满足至少三点:
1. 绑定一个固定的ip和port
2. 一直对外提供服务,稳定运行
3. 能够支持并发
# 服务端必须满足至少三点: # 1. 绑定一个固定的ip和port # 2. 一直对外提供服务,稳定运行 # 3. 能够支持并发 import socketserver # 自定义类用来处理通信循环 class MyTCPhanler(socketserver.BaseRequestHandler): def handle(self): while True: try: data = self.request.recv(1024) if len(data) == 0: break # 针对linux系统 print('-->收到客户端的消息: ', data) self.request.send(data.upper()) except ConnectionResetError: break self.request.close() if __name__ == '__main__': server=socketserver.ThreadingTCPServer(('127.0.0.1',8081),MyTCPhanler) server.serve_forever() # 链接循环
from socket import * client = socket(AF_INET, SOCK_STREAM) client.connect(('127.0.0.1', 8081)) # 通信循环 while True: msg=input('>>: ').strip() #msg='' if len(msg) == 0:continue client.send(msg.encode('utf-8')) #client.send(b'') client.send('hello'.encode('utf-8')) #client.send(b'') print('has send') data=client.recv(1024) print('has recv') print(data) client.close() 或 from socket import * client = socket(AF_INET, SOCK_STREAM) client.connect(('127.0.0.1', 8081)) # 通信循环 while True: client.send('hello'.encode('utf-8')) #client.send(b'') data=client.recv(1024) print(data) client.close()
基于udp协议通信
import socketserver class MyUdphandler(socketserver.BaseRequestHandler): def handle(self): data,sock=self.request sock.sendto(data.upper(),self.client_address) if __name__ == '__main__': server=socketserver.ThreadingUDPServer(('127.0.0.1',8081),MyUdphandler) server.serve_forever()
from socket import * client=socket(AF_INET,SOCK_DGRAM) while True: client.sendto(b'hello',('127.0.0.1',8081)) data,server_addr=client.recvfrom(1024) print(data)