Skip to main content
 首页 » 编程设计

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

2025年04月02日9lyhabc

我一直在研究一个将数据包发送到自身的其他副本的程序,并且 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 中删除条目以阻止抛出其他异常,因为您现在什么都不知道了。