小白练习笔记
import socket
client = socket.socket() #客户端实例化
client.connect(('localhost',9999)) #与服务器建立连接
while True: #循环发送指令
cmd = input(">>:").strip() #注意指令不小心输入的空格去掉
if len(cmd) == 0: continue #输入空信息时,防止客户端卡死,让用户重新输入
client.send(cmd.encode('utf-8')) #注意将指令从字符串转换为字节
cmd_res_size = client.recv(1024) #接收服务端发来的返回信息长度值
print('数据长度',cmd_res_size)
client.send('1'.encode('utf-8')) #发送确认数据,标识接收到数据长度信息
received_size = 0 #返回值长度属性
received_data = b'' #返回值具体数据
while received_size < int(cmd_res_size.decode()): #循环接收数据直到达到长度阀值
data = client.recv(1024) #每次接收1024
received_size += len(data) #计算接收到的长度
#print(data.decode())
received_data += data #接收的数据
else:
print('cmd res receive done...',received_size)
print(received_data.decode())