如何在Python中捕获socket.io异常

dso*_*sot 2 python python-socketio

我正在开展一个班级项目,我们正在尝试捕获 socket.io 异常。具体来说,socketio.exceptions.ConnectionError:连接被服务器拒绝我们这样做的目的是在尚未建立连接的情况下继续尝试连接。

我们尝试查看https://python-socketio.readthedocs.io/en/latest/上的文档,但找不到任何内容。同样,如果尚未建立连接,我们将尝试连接到服务器。我们正在研究 socket.reconnect() 但这似乎只有在建立连接后才起作用。我们正在尝试在树莓派 3 上实现这一点。我们编写了一个脚本来在启动时执行客户端代码,但在执行脚本后将与 pi 建立以太网连接。


import socketio
import opc, time
import json

# Initiate socket client
socket = socketio.Client()

# Initiate socket client for fadecandy server (little chip between Led strip and Pi
fade_client = opc.Client('localhost:xxxx')

# Establish connection to server
socket.connect("website url", namespaces=['/pi'])

# stuff to do after connection, mainly change led lights through
# fadecandy server
Run Code Online (Sandbox Code Playgroud)

小智 5

这应该对你有用:

connected = False
while not connected:
    try:
        socket.connect("website url", namespaces=['/pi'])
    except socketio.exceptions.ConnectionError as err:
        print("ConnectionError: %s", err)
    else:
        print("Connected!")
        connected = True
Run Code Online (Sandbox Code Playgroud)

谷歌“python try except”来了解如何捕获异常。