1. 程式人生 > 實用技巧 >python socket粘包

python socket粘包

server:

import socket,os


server = socket.socket()
server.bind(("localhost",9999))
server.listen()


while True:
conn, addr = server.accept()
while True:
data= conn.recv(1024)
print("接受成功",data)
if not data:
print("客戶端已經斷開")
break
print("執行指令",data)

cmd_res =os.popen(data.decode()).read()
print("before send ",len(cmd_res))
if len(cmd_res)==0:
cmd_res = "cmd has no putput"
conn.send(str(len(cmd_res.encode())).encode("utf-8"))
client_rec = conn.recv(1024)#去掉粘包
conn.send(cmd_res.encode("utf-8"))
print("send done ...")
server.close()


client:

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"))
print("傳送成功")
cmd_res_size = client.recv(1024) #接收這條命令執行結果的大小
print("命令結果的大小",cmd_res_size)
client.send("準備好接收了,發吧loser".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()