Sockets not going away

Dave Kennedy dave at poptech.coop
Fri Nov 23 09:11:43 EST 2007


Hi,

 

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], "..."

    httpd.serve_forever()

 

 

if __name__ == '__main__':

    test()

 

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 = '192.168.4.34'

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:

    sockobj.send(line)

    data = sockobj.recv(1024)

    print 'Client received:', repr(data)

 

sockobj.close()

 

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.

 

Thanks,

 

Dave

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20071123/51f6a109/attachment.html>


More information about the Python-list mailing list