Toy http server

Stefan Sonnenberg-Carstens stefan.sonnenberg at pythonmeister.com
Wed Dec 22 17:34:28 EST 2010


Sorry, this one is cross post.
I posted my question below some time ago to then jython ml, because this
hit me first with jython.
Anyway, time passed, problem not solved.

So, I'd like to know if some of you know where my error lies:


Hi all,

I've played around with some code-kata of mine from the past.
It's a toy http server:

import socket
import select
import sys
import time
srv = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
srv.setblocking(0)
srv.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True) # Not sure if 
this is needed. I only remember I've started once for some reason. 
Commenting out does no change
if srv:
     srv.bind(('',8080))
     srv.setblocking(0)
     srv.listen(5)
     conns = [srv]
     buffers = {}
     while True:
         reader,writer,failed = select.select(conns,conns,[],1)
         if failed:
             sys.exit(1)

         if srv in reader:
             client,(ip,port) = srv.accept()
             client.setblocking(False)
             conns += [client]
         for r in reader:
             if r is not srv:
                 data = r.recv(1024)
                 if not data:
                     conns.remove(r)
                 else:
                     if r in buffers:
                         buffers[r] += data
                     else:
                         buffers[r] = data
         for w in writer:
             if w is not srv:
                 if w in buffers and buffers[w][-2:] == '\r\n':
                     msg = 'HTTP/1.0 200 OK\r\nServer: 
Jython/2.5\r\nContent-type: text/plain\r\n\r\nThe answer is: 42\r\n'
                     w.send(msg)
                     w.close() # THIS ONLY WORKS WHEN THIS LINE IS PRESENT
                     conns.remove(w) # AND THEN THIS IS MUST
                     buffers[w] = ''

But today I was asking myself why I should always close the socket, and 
if wouldn't be more efficient if
I let it open.
To make a long story short: it does not work.
If I comment out the lines with the comment all upper case,
jython consumes one core in my laptop completely and ab.exe from apache 
bails out after a while.

Changing send() to sendall() did not do the trick.

I've searched the web and did not find anything meaningful.

Perhaps someone here can switch the light on.



More information about the Python-list mailing list