python - 多个连接到套接字时的 recvfrom() 行为

标签 python python-2.7 sockets recvfrom

我一直在研究一个将数据包发送到自身的其他副本的程序,并且 recvfrom 一直以一种我不完全理解的方式运行。该程序的每个实例都设置在不同的端口上(知道其他实例的端口号已经存储在 dictMap 字典中)。我的想法是,在我启动了该程序的多个实例(比如 8 个)之后,它们都应该每秒互相 ping 3 次 (MINI_UPDATE_INTERVAL)。

但是,如果我在一大堆正在运行的情况下关闭其中一个实例,所有程序都会继续打印“检测到丑陋的断开连接等”。多次,即使实例断开连接只断开一次。这背后的原因是什么?我的部分代码如下:

PORT = int(args.port)
socket.setdefaulttimeout(1)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,0)#make udp socket and use it to connect
s.bind(("",PORT))
s.setblocking(False)


#timing considerations
STARTTIME = time.time()
prevsent = STARTTIME


print "Node started..."
while True:

    readable, writable, err = select.select([s],[s],[s]) #using select to poll our socket to see if it is readable

    for sock in writable:#if s is writable (it should be), there are packets in the send queue AND one of the next two conditions is met:
        if forwardQueue:
            msgArr = forwardQueue.pop(0)
            sock.sendto(msgArr[MSG],("127.0.0.1",int(msgArr[DESTPORT])))


    for sock in readable: #if there's something to be read...
        try:
            recvMsg, addr = sock.recvfrom(2048)
        except:
            print "ugly disconnect detected" + str(addr[1]) + recvMsg
            break



    for sock in err:
        print "ERROR"



    if time.time() - MINI_UPDATE_INTERVAL > prevsent: #once a second
        # print time.time() - STARTTIME

        for key,value in dictMap.iteritems():
            forwardQueue.append([('PING'+ '|'+idName+'|'+str(time.time())),value])

编辑:问题似乎只发生在 Windows 上(WSAECONNRESET 在断开连接后不断弹出)。由于我的代码最终用于 linux,我想这没什么大不了的。

最佳答案

我相信每次您尝试将数据包发送到主机上的端口时都会遇到错误,而该端口上没有任何内容正在监听(或者监听积压已满)。

我建议从异常处理程序中的 dictMap 中删除条目以阻止抛出其他异常,因为您现在什么都不知道了。

关于python - 多个连接到套接字时的 recvfrom() 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40154957/

相关文章:

python - 我可以在 python 中编写忽略特殊字符(如逗号、空格、感叹号等)的代码吗?

python - 从查询集值访问 Django 模板上的外键

python - Scrapy:无法从我的项目数据(价格)中删除 unicode

java - 在 2 个线程唤醒之前,JFrame 不会显示组件

python - 从python中的相关矩阵中找到峰值

python-2.7 - 有没有办法使用Python在谷歌电子表格上自动生成图表?

python - 禁用 iPython Notebook 自动滚动

android - WifiP2pInfo.groupOwnerAddress.getHostAddress() IP 错误

c - C 中的 UDP 套接字

python - 如何从 Python 中获取 "slice"或从 BLPAPI 中的订阅中获取特定值?