python - 作为客户端,如何避免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()
?它似乎总是第一个没有关闭的连接。有任何想法吗?
解决方案
推荐阅读
- javascript - 获取 Cookie Volume 并为 JavaScript 设置
- python - re.findall 返回单独的非重叠结果
- android - 单击后通知无法消失,并且 Notification setAutoCancel(true) 不起作用
- raspberry-pi - 如何在树莓派上安装 pandasdmx
- jquery - jquery 验证和 jquery ajax 插件表单提交
- r - 当我使用 as.numeric 时,我所有的纬度和经度都变为“1”
- hadoop - HBASE 与 HIVE:哪个更适合由多个字段唯一定义的数据?
- nuxt.js - Nuxt.js 在服务器目录中转译文件
- python - 无法在 Python 上安装表
- ios - WKWebView 中的 PDF 被导航栏截断?