简体   繁体   中英

maintaining socket connection, irregular data frequency

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.

Eg:

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM