Sockets not going away

Dave Kennedy dave at
Fri Nov 23 15:11:43 CET 2007



I'm getting to grips with sockets and http servers in Python. I have
this bit of code which should be enough for a simple web demo


import socket, os

from BaseHTTPServer import HTTPServer

from SimpleHTTPServer import SimpleHTTPRequestHandler


def test(HandlerClass = SimpleHTTPRequestHandler,

         ServerClass = HTTPServer):

    server_address = ('', 8000) # (address, port)

    httpd = ServerClass(server_address, HandlerClass)

    sa = httpd.socket.getsockname()

    print "Serving HTTPS on", sa[0], "port", sa[1], "..."




if __name__ == '__main__':



I've noticed though that every time I connect to this server in
Firefox/IE, it seems to leave a socket behind. If I view the output of
netstat on the server, I can see a number of connections still seem to
be there.


Also, using the echo server and client programs from the O'Reilly
Programming Python book, I find that while the server doesn't seem to
leave connections behind, the client application does


import sys

from socket import *

serverHost = ''

serverPort = 50007


message = ['Hello network world']

if len(sys.argv) > 1:

    serverHost = sys.argv[1]

    if len(sys.argv) > 2:

        message = sys.argv[2:]


sockobj = socket(AF_INET, SOCK_STREAM) 

sockobj.connect((serverHost, serverPort))


for line in message:


    data = sockobj.recv(1024)

    print 'Client received:', repr(data)




How do I make sure that all my sockets have been completely disposed of?
I'm wanting to use Python to implement a client-server application, but
experience so far seems to be that after a flurry of network activity,
Python will use up all the available sockets.





-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list