python tcp断了自动连接
时间: 2024-09-06 18:06:59 浏览: 46
在Python中,如果你需要创建一个TCP客户端,它能自动检测并恢复与服务器的连接如果连接中断,通常会通过异常处理和定时重连机制来实现。以下是一个基本的示例:
```python
import socket
import time
def establish_connection(host, port):
while True:
try:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, port))
print("Connected to server")
break
except ConnectionRefusedError as e:
print(f"Connection refused, retrying in 5 seconds... ({e})")
time.sleep(5)
def main():
host = 'your_server_ip'
port = 8000 # Replace with your server's port
establish_connection(host, port)
# ... do your communication here
# Add a loop or event-based system to continuously check connection and reconnect if needed
if __name__ == "__main__":
main()
```
在这个例子中,`establish_connection`函数尝试连接到服务器,如果连接失败(如`ConnectionRefusedError`),则等待5秒后再次尝试。主程序中可以加入相应的循环或事件驱动结构,持续监控连接状态,并在连接丢失时自动恢复。
阅读全文