防止连接套接字在Python中关闭

时间:2012-07-25 13:34:13

标签: python sockets

我的功能类似于客户端。它会发送一条事件消息并等待确认(为简单起见,我删除了该部分)。之后它会收到更多消息:

def send_data(message):
    """Connect to server and get requests"""
    sock = socket.socket()
    host = 'localhost'
    port = 8000
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((host,port))

    try:
        if message:
            sock.sendall(message)

        # Look for the response
        has_request = False
        while not has_request:
            data = sock.recv(1024)

            #First I get ACK, code not listed here...
            #Next iteration, I got my request message
            has_request = True

    finally:
        print >> sys.stderr, 'Closing socket'
        sock.close() 

    return data

我在__main__声明中称呼它:

if __name__ == '__main__':
    server_data = send_data(event)

    if server_data:
        parse_request(server_data)

但是我需要防止套接字自动关闭。因为我在解析请求后必须发送另一条消息。我删除了sock.close(),但套接字仍然关闭。这是因为我正在撤回数据并且我不在函数范围内吗?

我只是想在我的程序中随时连接,然后接收和发送消息而没有任何问题。

1 个答案:

答案 0 :(得分:2)

当你超出send_data方法时,你的套接字sock将不再被任何人引用,因此垃圾收集器将完成他的工作并删除该对象,从而关闭套接字(即使没有close()电话)。

如果您使用数据返回套接字对象并将其放入主要部分,则套接字仍会被引用而不会被关闭。

def create_socket():
    sock = socket.socket()
    host = 'localhost'
    port = 8000
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((host,port))
    return sock

def send_data(message, sock):
    """Get requests"""
    if message:
        sock.sendall(message)

    # Look for the response
    has_request = False
    while not has_request:
        data = sock.recv(1024)

        #First I get ACK, code not listed here...
        #Next iteration, I got my request message
        has_request = True
    return data

if __name__ == '__main__':
    server_sock = create_socket()
    server_data = send_data(event, server_sock)

    if server_data:
        parse_request(server_data, server_sock)

    #no more use of server_socket ? 
    server_sock.close()