Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if data available in sockets in python

I want a functionality to check if data is waiting in the socket to be read before reading it. Something like this would be helpful:

if (data available) then read data

else wait in blocking mode till data becomes available

How can I achieve this in Python

like image 345
Vivek V K Avatar asked Apr 29 '14 04:04

Vivek V K


People also ask

How do you check if a socket is connected disconnected in Python?

The python socket howto says send() will return 0 bytes written if channel is closed. You may use a non-blocking or a timeout socket. send() and if it returns 0 you can no longer send data on that socket.

What is sendall in Python?

sendall is a high-level Python-only method that sends the entire buffer you pass or throws an exception. It does that by calling socket. send until everything has been sent or an error occurs.


1 Answers

while 1:
  socket_list = [sys.stdin, s]
  # Get the list sockets which are readable
  read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
  for sock in read_sockets:
   #incoming message from remote server
   if sock == s:
      data = sock.recv(4096)
      if not data :
        print '\nDisconnected from server'
        sys.exit()
      else :
         #print data
         sys.stdout.write(data)


   #user entered a message
   else :
     msg = sys.stdin.readline()
     s.send(msg)
like image 80
Nandha Kumar Avatar answered Oct 09 '22 23:10

Nandha Kumar