tcp protocol sticking problem
Posted by damnsaiyan on Wed, 31 Jul 2019 04:25:16 +0200
Sticky packet problem is caused by the way of streaming data transmission in tcp protocol
Give an example:
from socket import *
client = socket(AF_INET, SOCK_STREAM)
client.connect(('127.0.0.1', 8081))
# Communication cycle
while True:
cmd=input('>>: ').strip()
if len(cmd) == 0:continue
client.send(cmd.encode('utf-8'))
cmd_res=client.recv(1024)
print(cmd_res.decode('gbk'))
client.close()
Client
# The server must satisfy at least three points:
# 1. Binding a fixed ip and port
# 2. Always providing services to the outside world,stable operation
# 3. Ability to support concurrency
from socket import *
import subprocess
server = socket(AF_INET, SOCK_STREAM)
server.bind(('127.0.0.1', 8081))
server.listen(5)
# Link loop
while True:
conn, client_addr = server.accept()
print(client_addr)
# Communication cycle
while True:
try:
cmd = conn.recv(1024) #cmd=b'dir'
if len(cmd) == 0: break # In the light of linux system
obj=subprocess.Popen(cmd.decode('utf-8'),
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout=obj.stdout.read()
stderr=obj.stderr.read()
print(len(stdout) + len(stderr))
conn.send(stdout+stderr)
except ConnectionResetError:
break
conn.close()
server.close()
At each run time, when the amount of data is too large, the result of the next command is the result of the last undelivered command.
How to solve the sticky packet problem: the receiver can accurately collect every packet without any residue
from socket import *
client = socket(AF_INET, SOCK_STREAM)
client.connect(('127.0.0.1', 8081))
# tcp The protocol combines data with a small amount of data and a short time interval to send a datagram.
client.send(b'hello')
client.send(b'world')
client.send(b'egon')
Client
from socket import *
server = socket(AF_INET, SOCK_STREAM)
server.bind(('127.0.0.1', 8081))
server.listen(5)
conn,_=server.accept()
data1=conn.recv(5)
print('First time: ',data1)
data2=conn.recv(5)
print('Second collection: ',data2)
data3=conn.recv(4)
print('Third Harvest: ',data3)