views:

32

answers:

1

here is my dirty little web server :

class Serverhttp:
def __init__(self):
    self.GET = re.compile("GET.*?HTTP")
    self.POST = re.compile("POST.*?HTTP")
    try :
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_address = ('localhost', 36000)
        print >>sys.stderr, 'starting up on %s port %s' % server_address
        sock.bind(server_address)
    except :
        time.sleep(2)
        self.__init__()
    # Listen for incoming connections
    sock.listen(1)
    off = 2
    self.message = ""
    while True:
        # Wait for a connection
        print >>sys.stderr, 'waiting for a connection'
        if off == 2 or off == 1:
            connection, client_address = sock.accept()
        try:
            print >>sys.stderr, 'connection from', client_address

            # Receive the data in small chunks and retransmit it
            while True:
                data = connection.recv(1024)
                print >>sys.stderr, 'received "%s"' % data
                if data:
                    self.message = self.traitement(data)
                    connection.sendall(self.message)
                    connection.close()
                    connection, client_address = sock.accept()

                else:
                    print >>sys.stderr, 'no more data from', client_address
                    break

        finally:
            # Clean up the connection
            connection.close()
            sock.close()
            del(sock)

it works more or less but if i quit the server the port is still open and i can't reconnect on the same port. So i'am looking for a way to kill precedent socket or to exit in a nice way. Regards and thanks

Bussiere

+3  A: 

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

Should do the trick.

adamk
it did it thanks a lot and regards for this response.
Don't forget to accept the answer... 0% look pretty bad...
Ivo Wetzel