socket closing problem

Gandalf gandalf at geochemsource.com
Thu Jul 8 09:42:29 CEST 2004


>                 try:
>                     data = self.client_socket.recv(BUF_SIZE)
>                 except socket.error, msg:
>                     print "Error receiving data"
>                     break
>                 if not data:
>                     print "all data received"
>                     break 

...

>
> I thought that this would trigger the 
> "data=self.client_socket.recv(BUF_SIZE)"
> from the client_connection class in such a way that it would produce an
> exception or return empty data so i could close the thread gracefuly.
> Apparently this doesn't happen.
>
> When the server initiates the closing of the socket, then all happens 
> fine.
> How can i solve this & what am i doing wrong? 

Well, here is what you need to know:

1. First you should call select.select on the socket. Then you will know 
if there is data arrived from the server.
2. If so then you should call client_socket.recv(). Please note that if 
you call recv() BEFORE any data has arrived, it will block your program. 
(Sockets are defaulting to blocking sockets.)
3. Then you should examine the data received. There are two possibilities:

    a.) Your 'data' is not empty -> process the data
    b.) Your 'data' is empty. -> it means that the server closed the 
connection.

Conclusion: when select.select tells there is more data coming but you 
can only recv an empty string >>>  it means that the socket has been 
closed from the other site. You need to call both select.select and recv 
to detect if the socket is closed or not. The same procedure works on 
the server side (with the client socket) too.

Another note: you can call select.select on the server socket if you 
want to know when a client wants to connect to your server.

Best,

   G





More information about the Python-list mailing list