Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to check whether the data buffer for a socket is empty or not in python?

Tags:

python

sockets

I want to verify if the socket data buffer is empty or not before calling socket.recv(bufsize[, flags]). Is there a way to do that?

like image 928
Eduard Niesner Avatar asked Jan 31 '26 08:01

Eduard Niesner


2 Answers

You can peek (look without actually consuming the data):

data = conn.recv(bufsize, socket.MSG_PEEK)
like image 150
Hanuman Avatar answered Feb 01 '26 20:02

Hanuman


You might want to make your socket non-blocking:

socket.setblocking(0)

After that call, if you read from a socket without available data it will not block, but instead an exception is raised. See socket.setblocking(flag) for details.


For more advanced uses, you might look at select. Something like:

r, _, _ = select([socket],[],[],0)
#                               ^
#           Timeout of 0 to poll (and not block)

Will inform you if some data are available to read in your socket.

like image 29
Sylvain Leroux Avatar answered Feb 01 '26 20:02

Sylvain Leroux