[Tutor] SocketObject.close() question

Michael P. Reilly arcege@speakeasy.net
Wed, 13 Feb 2002 14:16:03 -0500

On Wed, Feb 13, 2002 at 04:11:36PM +0100, Andreas Sch=F6ller wrote:
> Hello tutors,
> i=B4m using the xmlrpclib library 0.9. and the xmlrpcsvr.py script wich=
> creates a SocketServer at a specified port. The socket-object has a=20
> close()-method which works as expected - after calling the method the=20
> socket gets closed and further connections are refused. But when i try=20
> to restart the xmlrpc-Server on the same port i get the message =20
> socket.error: (48, 'Address already in use'). After 1-2 minutes it=B4s=20
> possible to reuse the server on that port again ? Is this behavior=20
> considered normal or am I wrong in closing the socket by using=20
> socket.close() ?
> I=B4m on a Mac OsX 10.1.2 - is this a system library dependent behaviou=
r ?
> thanks for your support,, andreas

Specifically, that's a socket-dependant, system-independant behavior;
and yes, it is normal.

You can change a socket to reuse the same address, since the socketserver
class is being used, you can maybe get the xlmrpcsvr to take a subclass
of that.

class ReuseSocketServer(SocketServer):
  def server_bind(self):
    import socket
    self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

Also, you might want to think about using the shutdown() method instead
of just close().  This will allow the network protocols to come down
gracefully, and will reduce the number of "already in use" errors (not
not all of them).  There is nothing strictly wrong with using close, but
you will want to make sure that the socket isn't connected by some means.

Think about a telephone: it is possible, though unprobable, that someone
could call at the same time you pick up the handset to make a call.
This causes the phone to not ring, and the connection to go through;
you start dialing the number and the other end is going "hello".
This happens in real, but it's rare.  Now think about if it was at the
other end of the call - someone was calling when you were hanging up,
the connection might be established, your phone would think the call was
done, but possibly the hardware in between left the connection open.

The phone systems do not allow this "feature", but the TCP networks do.
It's better to just use "shutdown" to let the whole system know you are
shutting down.