Processing of sticky packets in network programming (socket) and network programming socket
Server
Import socket, OS
Service = socket. socket ()
Service. bind ('localhost', 1024) # bind the port to be listened on
Service. listen () ### listening port
Con, adder = service. accept () # Wait for the other party's connection, generate an instance of the other party's connection in the region, and assign a value to con
While True:
Data = con. recv (1024). decode ('utf-8') # receive the value passed by the other party (the maximum value received is 2222 bytes) and assign a value
X = OS. popen (data). read ()
Con. send (str (len (x). encode ('utf-8 '))
# Time. sleep (0.5) ### avoid sticking packets, but there will be latency (not recommended)
Check_ack = con. recv (1024) # one interaction is performed between two send messages to prevent sticking to the package (recommended). At the same time, the client also responds.
Con. send (x. encode ('utf-8') # send data to the recipient
Service. close ()
Customer Service
Import socket
Client = socket. socket ()
Client. connect ("localhost", 1024 ))
While True:
Msg = input (':'). encode ('utf-8 ')
Client. send (msg)
Datasize = client. recv (1024). decode ('utf-8 ')
Client. send ("I have received it, you can pass the following content". encode () ### the client performs an automatic confirmation.
X = 0
While x! = Int (datasize ):
A = client. recv (1012). decode ('utf-8 ')
X + = len ()
Print ()
Else:
Print (datasize, x)