【问题标题】:Python : Closing a socket already opened by a precedent python program or dirty trick to close a socketPython:关闭已由先前的 Python 程序打开的套接字或关闭套接字的肮脏技巧
【发布时间】:2010-10-11 11:41:54
【问题描述】:

这是我肮脏的小网络服务器:

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)

它或多或少地工作,但如果我退出服务器,端口仍然打开,我无法在同一个端口上重新连接。所以我正在寻找一种方法来杀死先例套接字或以一种好的方式退出。 问候和感谢

布西耶

【问题讨论】:

  • -1:当您可以使用库中已内置的wsgirefBaseHTTPServer 时编写自己的。如果你不打算使用内置的HTTP服务器,请停止使用内置的socket库,直接使用/dev/eth驱动。

标签: python sockets kill shutdown


【解决方案1】:

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

应该做的伎俩。

【讨论】:

    猜你喜欢
    • 2014-04-03
    • 2014-09-18
    • 1970-01-01
    • 2014-09-09
    • 2013-10-19
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    • 2014-03-01
    相关资源
    最近更新 更多