August 7th, 2003, 03:05 AM
a few socket questions...
Two Python-newbie questions...
Say I have a server-side socket that is set to listen, and I want it non-blocking. But when I try to do this:
I get this...
>>> import socket
>>> server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> server_socket.bind((socket.gethostname(), 4000))
>>> (conn, addr) = server_socket.accept()
I realize I could do this as a quick fix:
File "<pyshell#6>", line 1, in -toplevel-
(conn, addr) = server_socket.accept()
File "C:\dev\Python\lib\socket.py", line 167, in accept
sock, addr = self._sock.accept()
error: (10035, 'The socket operation could not complete without blocking')
But that's hardly elegant, really. Is there a better way?
insock, outsock, errsock = select.select([server_socket], , , 0)
# insock has at most 1 element, 0 if no connections pending...
for sock in insock:
new_conn, addr = sock.accept()
# do whatever with new_conn....
All my established connections are in an array of sockets (in fact, after I get new_conn above from server_socket.accept(), I append it to my array of sockets/established connections, and then perform select on that array -- which makes sense, because I want to find what sockets out of many need attention...). But after, say, 3 minutes of not sending/receiving data over a socket, i'd just like to send a packet and have it echo back to make sure the connection is still alive (I could define/code this function, but there wouldn't happen to be a built-in Python function that confirms the validity of a connection, would there?). After 5 minutes, I'd like to tear down the connection/close the socket. Can I bind timers (do they exist?) to socket objects to signal when 3/5 minutes have passed?
The other way (and probably easier way) I was thinking of would be when I send/receive over a socket, update a table that records when I last used the socket. Also, periodically go to the table and find sockets that haven't been used in over 3/5 minutes, and either check their validity/remove them. If the first way is possible, would this be better?
Last edited by theperfectsoup; August 7th, 2003 at 03:11 AM.
August 7th, 2003, 06:18 AM
The problem is that, when you do setblocking(False), it really means settimeout(0.0). Then you do an accept, which means "wait for an incoming connection". Waiting for an incoming connection and having 0.0 as timeout value is sort of contradictory. (Or, at least, I think this is the problem.)
Maybe you should look at asyncore?
Last edited by percivall; August 7th, 2003 at 06:21 AM.