套接字异常无法在python中重新连接到网络

时间:2018-10-06 04:32:08

标签: python sockets reconnect

当网络脱机时,套接字会引发错误,而不是重新连接。它正在重新连接,但未尝试建立连接。在第二次或第三次尝试中引发错误。我是否需要增加等待时间或是否可以添加任何内容以确保重新连接发生

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

0 个答案:

没有答案