3

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

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() 但套接字仍然关闭。这是因为我正在返回数据并且我超出了函数范围吗?

我只想在我的程序中随时连接,然后毫无问题地接收和发送消息。

4

1 回答 1

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()
于 2012-07-25T13:39:31.590 回答