Python:关闭由先前程序打开的套接字或关闭套接字的窍门

0 投票
1 回答
2010 浏览
提问于 2025-04-16 05:19

这是我写的一个简单的网页服务器:

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)

它大致上能工作,但如果我退出服务器,端口还是开着的,我就不能再用同样的端口重新连接。所以我在找一种方法来关闭之前的连接,或者优雅地退出。
谢谢!

祝好,
Bussiere

1 个回答

4

这行代码的意思是:给一个叫做“sock”的网络连接设置一个选项,让它可以重用地址。

简单来说,这样做可以让你在程序运行时,如果需要重新启动这个连接,就不会因为地址还在被占用而出错。

最后的“Should do the trick”可以理解为“这样做应该就能解决问题”。

撰写回答