How to solve the sticky package problem with python
Editor to share with you python how to solve the sticky package problem, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to understand it!
1. Know the size of the data sent and set the size of the reception, so that you can receive all the data exactly. The sticky packet problem is due to the combination of two small packets sent by tcp's optimization algorithm.
This usually happens when several send () are used in succession.
This is the program that remotely executes the cmd command and returns the result. The server side code import structimport socketsk = socket.socket () sk.bind (('127.0.0.1) sk.bind ((' 127.0.0.1)) sk.listen () conn,addr = sk.accept () while True: cmd = input ('> >') conn.send (bytes (cmd) Encoding='utf-8') num = conn.recv (1024). Decode ('utf-8') # data length calculated by the client end conn.send (bytes (' ok',encoding='utf-8')) # when sending a confirmation to prevent sending num, merge ret = conn.recv (num) print (ret.decode ('gbk') conn.close () sk.close () with the following send content
2. Use struct module to solve the adhesion phenomenon.
Solution to the sticky package phenomenon of # tcp Code on server structimport structimport socketsk = socket.socket () sk.bind (('127.0.0.1) sk.bind ((' 127.0.0.1)) sk.listen () conn,addr = sk.accept () while True: cmd = input ('> >') conn.send (bytes (cmd) Encoding='utf-8') # num = conn.recv (1024). Decode ('utf-8') num = conn.recv (1024) # receive data num = struct.unpack (' iMagnum) [0] # to unpack The result of unpacking is that a tuple type takes the first data # conn.send (bytes ('ok',encoding='utf-8')) ret = conn.recv (num) print (ret.decode (' gbk')) conn.close () sk.close () above is all the contents of the article "how to solve the sticky package problem with python". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!