Python | Websockets communication long connection, network disconnection reconnection, connection exception handling

The client establishes a long connection with the server to realize the disconnection reconnection mechanism

import asyncio
import websockets
import time

async def con():
    print("准备连接!")
    while True:
        try:
            async with websockets.connect( 'ws://1.1.1.1:8080/imserver/400') as websocket:
                print("websocket 连接成功")
                while True:
                    try:
                        message = await websocket.recv()
                        print("接收到的消息:{}".format(message))
                        time.sleep(1)
                    except websockets.exceptions.ConnectionClosedError as e:
                        print("connection closed error")
                        print("连接被异常关闭,3秒后开始重连")
                        time.sleep(3)
                        break
                    except Exception as e:
                        print(e) 
        except Exception as e:
            print(e)
            print("重连失败!")
            print("五秒后将继续重连!")
            time.sleep(5)

asyncio.get_event_loop().run_until_complete(con())

Guess you like

Origin blog.csdn.net/holly_Z_P_F/article/details/129974703