Python socket的客戶端

桐原發表於2019-02-11
做一個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()

相關文章