Python套接字库认为套接字在未打开时处于打开状态 [英] Python socket library thinks socket is open when it's not

查看:85
本文介绍了Python套接字库认为套接字在未打开时处于打开状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一些看起来像这样的Python:

I'm working with a bit of Python that looks like this:

HOST = '127.0.0.1'
PORT = 43434
single = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    single.bind((HOST, PORT))
except socket.error as e:
    # Print an error, exit.

虽然过去一直运行良好,但现在出现错误[Errno 98] Address already in use. SIGINT处理程序会关闭套接字连接,因此我不确定它是如何进入该状态的,但是现在我只是在尝试对其进行修复.

While it's been functioning well in the past, we now get the error [Errno 98] Address already in use. The SIGINT handler closes the socket connection, so I'm not sure how it got in that state, but for now I'm just trying to fix it.

lsofnetstat都说没有使用该端口的东西:

Both lsof and netstat say there's nothing using that port:

[$]> sudo netstat -an | grep 43434
[$]> sudo lsof -i :43434

根据/proc/sys/net/ipv4/tcp_fin_timeout

TIME_WAIT设置为60秒,但即使上次成功运行数小时,也会发生错误.

TIME_WAIT is set to 60 seconds, according to /proc/sys/net/ipv4/tcp_fin_timeout, but the error occurs even hours after last run successfully.

我尝试(暂时)通过single.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)设置REUSEADDR,但这似乎没有效果.

I've tried (temporarily) setting REUSEADDR (via single.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)), but that appears to have no effect.

发生什么事了?我将能够再次使用该端口而不必重新启动计算机吗?

What in tarnation is going on? Will I ever be able to use this port again without having to reboot the machine?

推荐答案

我想添加评论,但我不允许这样做.所以我必须这样回答.以我的经验,我必须执行以下操作才能使套接字成功运行.我必须自己明确设置超时时间.

I wanted to add a comment but It will not let me do so. so I have to answer this way. In my experience I have had to do the following to get sockets to work with any success. I've had to explicitly set the timeout myself.

在打开套接字之前的代码中,如果使用的是python 2.3或更高版本,则应进行设置.我通常以30秒的超时时间开始,然后将其调整为适用于特定网站的时间.当我不使用此参数时,我会遇到易燃问题.

In your code before you open the socket, you should set this if you are using python version 2.3 or later. I usually start with a timeout of 30 seconds and then tune it to what works for a particular website. When I don't use this parameter i get flakey issues.

socket.setdefaulttimeout(timeout)

开放后我遇到的其他问题有以下一些例外情况:

Other issues I've done after the open are catch some of the following exceptions:

            except socket.gaierror, err:
                # you might want to handle this
            except socket.sslerror, err2:
                # you might want to handle this if doing SSL

这篇关于Python套接字库认为套接字在未打开时处于打开状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆