开发者

Python : Closing a socket already opened by a precedent python program or dirty trick to close a socket

开发者 https://www.devze.com 2023-01-19 17:50 出处:网络
here is my dirty little web server : class Serverhttp: def __init__(self): self.GET = re.compile(\"GET.*?HTTP\")

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 开发者_如何学Goor 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


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

Should do the trick.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号