0

I'd like to create a python socket (or SocketServer) that, once connected to a single device, maintains an open connection in order for regular checks to be made to see if any data has been sent. The socket will only listen for one connection.

E.g.:

def get_data(conn):
    response='back atcha'
    data = conn.recv(1024)
    print 'get_data:',data
    if data:
        conn.send(response)

s = open_socket()
conn, addr = s.accept()
while True:
    print 'running'
    time.sleep(1)
    get_data(conn)
    #do other stuff

Once the server socket is bound and the connection has been accepted, the socket blocks when running a .recv until either the connecting client sends some data or closes its socket. As I am waiting for irregular data (could be seconds, could be a day), and the program needs to perform other tasks in the meantime, this blocking is a problem.

I don't want the client to close its socket, as it may need to send (or receive) data at any time to (from) the server. Is the only solution to run this in a separate thread, or is there a simple way to setup the client/server sockets to maintain the connection forever (and is this safe? It'll be running on a VLAN) while not blocking when no data has been received?

radpotato
  • 1,332
  • 1
  • 12
  • 20

1 Answers1

1

You're looking for non-blocking I/O, also called asynchronous I/O. Using a separate thread which blocks on this is very inefficient but it's pretty straightforward.

For a Python asynchronous I/O framework I highly recommend Twisted. Also check out asyncore which comes with the standard library.

Hut8
  • 6,080
  • 4
  • 42
  • 59
  • 1
    Nonblocking I/O and asynchronous I/O are two different things. – user207421 Mar 13 '13 at 22:15
  • Look [here](http://stackoverflow.com/questions/16745409/what-does-pythons-socket-recv-return-for-non-blocking-sockets-if-no-data-is-r) for examples how to use a non-blocking socket. – Armali Jun 06 '14 at 12:14