服務端json
1 from socket import * 2 import json,struct 3 4 client= socket(AF_INET,SOCK_STREAM) 5 client.connect(('127.0.0.1',8081)) 6 7 while True: 8 cmd=input('>>>').strip() 9 if not cmd:continue 10 client.send(cmd.encode('utf-8')) 11 # 先接受報頭長度 12 head_len=struct.unpack('i',client.recv(4))[0] 13 # 接收報頭 14 head_bytes=client.recv(head_len) 15 # 解析報頭 16 head_json=head_bytes.decode('utf-8') 17 head_dic=json.loads(head_json) 18 print(head_json) 19 total_size=head_dic['size'] 20 # 取出真實數據 21 recv_size=0 22 finnally_data=b'' 23 while total_size>recv_size: 24 recv_data=client.recv(1024) 25 finnally_data+=recv_data 26 recv_size+=len(recv_data) 27 print(finnally_data.decode('gbk')) 28 29 client.close()
客戶端socket
1 from socket import * 2 3 client=socket(AF_INET,SOCK_DGRAM) 4 5 while True: 6 msg=input('>>>').strip() 7 if not msg:continue 8 client.sendto(msg.encode('utf-8'),('127.0.0.1',8080)) 9 data,addr=client.recvfrom(512) 10 print(data.decode('utf-8'))