Python线程异常和套接字断开连接/WinError 10053

2024-04-20 13:00:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在套接字连接上运行心跳消息(它每30秒发送一条消息),所以我在它自己的线程上运行它,并尝试是否作为守护进程。我在一台虚拟机上--Windowsx86

程序运行正常,并传输消息,但在心跳的第12次迭代中,我开始得到“线程错误!”(我试过关闭防火墙,和机器相关的东西,但不知道连接是怎么回事/为什么会断开。我也递归地尝试过,没有线程——我收到winerror10053,建立的连接被主机中的软件中止

def every(delay, task):
    next_time = time.time() + delay
    while True:
        time.sleep(max(0, next_time - time.time()))
        try:
            task()
        except Exception:
            print('Error threading!')
        next_time += (time.time() - next_time) // delay * delay + delay

def test():
    print("Threadtest", time.time())

等级HB\U插座():

def __init__(self,IP='127.0.0.1',port=4000,hb = 30):
    self.IP = IP
    self.port = port
    self.HB = hb
    self.socket = socket() #AF_INET,SOCK_DGRAM)
    self.connected = False

def cnct(self):
    s = self.socket
    #s.connect((self.IP,self.port))                                         #MOVED THIS 
    try:  
        s.connect((self.IP,self.port))
        print('Socket connected to {} on port {}'.format(self.IP,self.port))

        on = self.logOn()
        self.send(on)
        print('LogOn message sent')

        self.connected = True
        return 1
    except:
        print('Socket creation failed: {}')
        return 0


#Function being called in every()
def sendHB(self):
    hbsocket = self.socket
    print('PyHeartBeat client sending to IP {}'.format(self.IP,self.port))
    #while 1:
    hbsocket.sendto(HB_MSG,('127.0.0.1',self.port))
    if HB_SIM:
        sleep(self.HB)
        if datetime.datetime.now().time().hour >= 16:                      
            self.disconnect()
            return
        self.sendHB()

if __name__ == '__main__':
    HB = HB_Socket()
    HB.cnct()

    HB_SIM = False
    threading.Thread(target=every,args=(30,HB.sendHB)).start()

    HB_SIM = True                      #Recursive solution.
    #HB.sendHB()

    #Daemon / Recursive
    dmn = threading.Thread(target=HB.sendHB(), daemon=True)
    dmn.start()

这是返回错误的图像 return in Spyder


Tags: selfiptrue消息timeportdefsocket