简体   繁体   中英

How catch socket.io exceptions in python

I am working on a class project and we are trying to catch a socket.io exception. Specifically, socketio.exceptions.ConnectionError: Connection refused by server The purpose of us doing this is to keep attempting to connect if not connection has been made.

We tried looking through the documentation at https://python-socketio.readthedocs.io/en/latest/ but could not find anything. Again, we are trying to attempt to connect to a server if connection has not been made. We were looking at socket.reconnect() but that appears to only work once a connection has been made. We are trying to implement this on a raspberry pi 3. We wrote a script to execute our client code on start up but the ethernet connection is made to the pi after the script is executed.


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

This should work for ya:

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

Google "python try except" to learn about catching exceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM