Fun with Sockets

posted: Tue, 28 Oct 2008 22:06 | filed under: / / / | permalink | Tags: , , | Comments: 2

Whilst doing some coding today for my semester research project I found a need to check for incoming data on a socket without taking any data out of the stream. Here's the code I came up with:

     
cp.sock.setblocking(False)
try:
    cp.sock.recv(0)
    stuffwaiting = True
except socket.error:
    stuffwaiting = False
cp.sock.setblocking(True)

This code works finely on Linux -- you can only receive data if there is data to be received (even if you want to receive no data). Unfortunately, the code doesn't port to Mac OS -- you may receive as many bytes as there are in the socket's buffer -- if there are no bytes in the buffer, you can receive 0 bytes. Therefore, the following fix is necessary:

     
cp.sock.setblocking(False)
try:
    cp.sock.recv(1, socket.MSG_PEEK)
    stuffwaiting = True
except socket.error:
    stuffwaiting = False
cp.sock.setblocking(True)

So, my question for Lazyweb is: is there a better way to do this?

Comments

Use Objective-C.

Posted by Paris at Wed Oct 29 21:52:05 2008


Is there any reason you can't just use select()?

Posted by Michael Olney at Sun Nov 9 17:59:51 2008


Leave a comment

Name:


E-mail:


URL: (Prefix with http://)


Comment: