python3 tcp stick pack phenomenon and solutions

Service-Terminal

import socket

sk = socket.socket()
sk.bind(("127.0.0.1", 6666))
sk.listen()
conn, address = sk.accept()


def my_send(msg):
    bs = msg.encode("utf-8")
    len_str = format(len(bs), "04d")  # 定长4位
    conn.send(len_str.encode("utf-8"))
    conn.send(bs)


my_send(input(">>>:").strip())
my_send(input(">>>:").strip())

 

Client

Import Socket
 Import Time 

SK = socket.socket () 
sk.connect (( " 127.0.0.1 " , 6666 )) 

the time.sleep ( 10)   # producing stick package case 
MSG = sk.recv (1024) .decode ( " UTF- 8 " )   # stick pack phenomenon 
Print (msg)

Results of the:

0004aaaa0003bbb

There are stick pack phenomenon.

 

Solve the stick package, the client code adjustment

import socket
import time

sk = socket.socket()
sk.connect(("127.0.0.1", 6666))
time.sleep(10)

def my_recv():
    len_str = int(sk.recv(4).decode("utf-8"))
    msg = sk.recv(len_str)
    print(f"来自服务端的消息:{msg.decode('utf-8')}")


my_recv()
my_recv()

Results of the:

Aaaa: message from the service side of the 
message from the service side: bbb

 

Guess you like

Origin www.cnblogs.com/lilyxiaoyy/p/12002690.html