服务端
from socket import *
import json,struct client= socket(AF_INET,SOCK_STREAM)
client.connect(('127.0.0.1',8081)) while True:
cmd=input('>>>').strip()
if not cmd:continue
client.send(cmd.encode('utf-8'))
# 先接受报头长度
head_len=struct.unpack('i',client.recv(4))[0]
# 接收报头
head_bytes=client.recv(head_len)
# 解析报头
head_json=head_bytes.decode('utf-8')
head_dic=json.loads(head_json)
print(head_json)
total_size=head_dic['size']
# 取出真实数据
recv_size=0
finnally_data=b''
while total_size>recv_size:
recv_data=client.recv(1024)
finnally_data+=recv_data
recv_size+=len(recv_data)
print(finnally_data.decode('gbk')) client.close()
客户端
from socket import * client=socket(AF_INET,SOCK_DGRAM) while True:
msg=input('>>>').strip()
if not msg:continue
client.sendto(msg.encode('utf-8'),('127.0.0.1',8080))
data,addr=client.recvfrom(512)
print(data.decode('utf-8'))