Search code examples
pythonsocketstcp

Python - sending urgent data (tcp)


I have a problem with sending urgent data in python via TCP.

I have studied the structure of TCP header and the out-of-band data transfer mechanism, but I still can't understand how to implement this..

simple server:

#default steps
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn,addr = s.accept()
...
#oob
conn.send('!',MSG_OOB)
...

simple client:

...
data = conn.recv(BUFFER_SIZE,MSG_OOB)

OK, data received.

But how can I indicate that OOB information has come to client when i send data in cycle?

For example:

serverFile = open(serverPath, 'rb')
    while True:
        fileBytes = serverFile.read(1000)
        if not fileBytes: break;
        try:
            i += 1
            if i % 1000 == 0:
                print 'sending urgent..'
                conn.send('!',MSG_OOB)
            conn.send(fileBytes)
        except socket.error, (value, message):
            if conn:
                conn.close()
            serverFile.close()
            print 'Error while sending data : error code - ' + str(value) + '; message: ' + message
            exit(1)
    serverFile.close()

If client tries to receive all data with 'data = conn.recv(BUFFER_SIZE,MSG_OOB)' - nothing works. I have not found any way to use SELECT or smth like SIGURG to solve problem.


Solution

  • Perhaps it will help someone (obvious but not particularly efficient solution): client:

    #catching urgent data
        s.settimeout(2)
        try:
            data = s.recv(BUFFER_SIZE,MSG_OOB)
        except socket.error, value: #(value,message):
            #s.settimeout(5)
            data = None
        if data:
            print 'urgent ' + str(data)
        else:
            #recv usual data
            data = s.recv(BUFFER_SIZE)