python - 套接字异常无法在 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
解决方案
推荐阅读
- python - pip install zbarlight 失败
- c# - 保存文件时的 MVC Dropzone.js 回发
- javascript - 返回具有参数传递的长度属性的数组
- angular - 在不触发 Angular v6 中的 eventemiiter 的情况下获取父级的子级值
- android - 通过单击按钮将值传递给 ListView
- reactjs - 我应该在 ReactJs 应用程序中测试什么?
- jboss - 更好的处理多个 jboss 实例的方法
- angularjs - 模板功能 VS 更大的模板
- node.js - Node.js 服务器请求 /inform
- python - 使用正则表达式匹配不以某个字母开头的单词