What is the correct way to close a socket in python 2.6?

I have a simple server / client. and I use netcat as a client to test the server. if I stop the server before the client exits, I will not be able to start the server for some more time, and I will take away this error: "[Errno 98] The address is already in use"

but if I close the client first, then the server will stop, I will not have this problem.

my server socket works as follows:

try: s=socket s.bind(..) s.listen(1) conn,addr=s.accept() finally: conn.close() s.close() 

It seems to me that the server did not close the socket properly. but I don’t know how to fix it.

+3
source share
1 answer

You close the socket just fine. However, the socket continues to use resources for several minutes after the socket is closed, so if the remote end missed the packet, the packet can be resent.

You should be able to get around this by calling the following before you call bind :

 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 

This will tell the operating system that you want to allow multiple socket bindings.

+9
source

All Articles