首页 > 解决方案 > 作为客户端,如何避免python中TCP/IP套接字中的CLOSE_WAIT?

问题描述

我想迭代地连接到 localhost 端口 6667 以获取一些数据。代码是这样的:

def get_data_from_socket(n):
    # making a socket
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:

        # resolving localhost’s ip
        host_ip = socket.gethostbyname('localhost')

        # connecting to the server
        s.connect((host_ip, 6667))

        # output the client socket ip and port 
        print('getsockname:{}'.format(s.getsockname()))

        # listening the port
        while True:

            # send message to the server
            s.sendall('get: {}'.format(str(n)).encode())

            # Getting a response from the server
            res = (s.recv(1024)).decode()

            # if the length of messages is not empty, stop listening the port.
            if len(res) > 0:
                # stop listening
                break
return res

def get_all_data_from_socket():
    res = ''
    for i in range(5):
         res += get_data_from_socket(i)
    return res

我运行python get_all_data_from_socket()一次并在终端中获得以下输出:

getsockname:('127.0.0.1', 43230)
getsockname:('127.0.0.1', 43232)
getsockname:('127.0.0.1', 43234)

之后,如果我运行以下命令

sudo netstat -tonp | grep CLOSE_WAIT

我总是得到一个CLOSE_WAIT连接,例如:

tcp6       1      0 127.0.0.1:6666          127.0.0.1:43230         CLOSE_WAIT  290779/java          off (0.00/0/0)

为什么我的代码在运行函数时并不总是关闭连接get_data_from_socket()?它似乎总是第一个没有关闭的连接。有任何想法吗?

标签: pythonsockets

解决方案


推荐阅读