首页 > 解决方案 > 套接字异常无法在 python 中重新连接到网络

问题描述

当网络离线时,套接字会抛出错误而不是重新连接。它正在重新连接,但没有尝试实现连接。在第二次或第三次尝试中引发错误。我需要增加等待时间还是可以添加任何东西以确保重新连接发生

import socket,time
client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)    
client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

ip = '192.168.xx.x'
port = 4196
address = (ip,port)

client.connect(address)
print("connecting")


while 1:
    try:
        client.send(b'\x01\x04xxxxxxx')
        print("sent")
        data = client.recv(1024)
        print(data)
        time.sleep(5)
    except socket.error:
        while 1:
            print("error")
            client.close()
            time.sleep(30)
            print("reconnecting")
            client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            while 1:
                client.connect(address)
                print("connected back")
                break        
            break

输出:

connecting
sent
01 04 xxxxxxxxx
error
reconnecting

错误:

Traceback (most recent call last):
  File "C:\Users\User\eclipse-workspace\Data\pwr\TCP.py", line 15, in <module>
    client.send(b'\x01\x04\xxxxxxxxxxx')
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

 During handling of the above exception, another exception occurred:  

Traceback (most recent call last):
  File "C:\Users\User\eclipse-workspace\Data\pwr\TCP.py", line 28, in <module>
    client.connect(address)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine

标签: pythonsocketsreconnect

解决方案


推荐阅读