粘包:两次数据粘到一起了。在Windows中基本看不出来效果。
服务器端的配置:
import socket,os,time server=socket.socket()
server.bind(('localhost',9999))
server.listen()
while True:
conn,addr=server.accept()
print("new connection is :",addr)
while True:
data=conn.recv(1024)
if not data:
print("客户端已经断开")
break
cmd_res=os.popen(data.decode('utf-8')).read()
if len(cmd_res)==0:
cmd_res="命令无效,没有返回值"
conn.send(str(len(cmd_res.encode())).encode('utf-8'))
#整数不能直接encode,需要先转成字符串,再encode.发大小给客户端
#time.sleep(0.5) #防止粘包
client_ack=conn.recv(1024) #wait client to confirm
print("ack from client:",client_ack)
conn.send(cmd_res.encode('utf-8'))
server.close()
客户端的配置:
import socket client=socket.socket()
client.connect(('localhost',9999))
while True:
cmd=input(">>:").strip()
if len(cmd)==0:
break
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("utf-8")):
data=client.recv(1024)
received_size=received_size+len(data) #每次收到的有效数字,有可能小于1024
received_data=received_data+data
else:
print("cmd res received done...",received_size)
print(received_data.decode('utf-8'))
client.close()