做一个socket客户端
1、声明一个实例
2、绑定端口号和地址
3、循环发送和接收响应
其中要注意粘包的产生,为了防止粘包的产生,应该在服务器端先测出要发送信息的大小,
然后发送响应至客户端,等到服务器上一条信息发送完毕,客户再响应准备好接收下一条信息
这样就不会有粘包的产生
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("我准备好了".encode("utf-8")) #响应服务器端发送请求,为防止粘包的产生
received_size = 0
received_data =b''
while received_size < int(cmd_res_size.decode()):
data = client.recv(1024)
received_size += len(data)
received_data += data
else:
print("cmd res receive done...",received_size)
print(received_data.decode())
client.close()
转载于:https://www.cnblogs.com/Benedict/p/10361167.html