Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python optimize packets in sending. How to prevent it?

Im trying to send 3 packets one after the other with python socket. Python optimize it to one or 2 packets. I prevented it by sleep command, but it takes too long time. I thought to turn on the TCP urg flag, Does someone know how to do it?

or you have another solotion?

client side:

import socket
from time import sleep

IP = '127.0.0.1'
PORT = 5081
BUFFER_SIZE = 1024


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, PORT))

s.send('1'*5)
#sleep( 1)
s.send('2'*5)
#sleep( 1)
s.send('3'*5)

s.close()

server side:

import socket

IP = '0.0.0.0'
PORT = 5081
BUFFER_SIZE = 1024


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((IP, PORT))
s.listen(1)

connection, address = s.accept()
while 1:
    #Here I expected to get the 1nd value
    data1 = connection.recv(BUFFER_SIZE)
    #end of communication
    if not data1:
        break
    print 'data1', data1

    #Here I expected to get the 2nd value,but both inputs arrived here, 22222 and 33333
    data2  = connection.recv(BUFFER_SIZE)
    print 'data2', data2

    #Here I expected to get the 3nd value
    data3  = connection.recv(BUFFER_SIZE)
    print 'data3', data3

connection.close()

thanks Avinoam

like image 621
avinoam Avatar asked Aug 11 '26 03:08

avinoam


1 Answers

You should not even try. TCP is a stream protocol and should be used as a stream protocol (meaning a single sequence of bytes). Even if you manage to maintain the separation of packets when you use localhost on your system, it could break if you use it between different hosts, or simply after an upgrade of the TCP/IP stack. And as soon as your packets will pass through a proxy or a software filter, anything can happen.

The correct way to separate different objects on a stream is to use an upper level protocol encoding the objects sender side and decoding them client side. An example of that is one or two bytes (in network order if more than one byte) for the size followed by the relevant bytes. Or you could imagine a text protocol with commands, headers and data, or [put whatever you want here]

like image 191
Serge Ballesta Avatar answered Aug 12 '26 18:08

Serge Ballesta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!