raise exceptions.ConnectionError(exc.args[0]) from None socketio.exceptions.ConnectionError: Connection error

101 views Asked by At

I am learning the python-socketio with below simple server and client examples.i write the code and it works fine.

Server.py

import socketio


sio = socketio.Server(async_mode='eventlet')

# Web Server Gateway Interface
app = socketio.WSGIApp(sio)

connected_clients = {}


@sio.event
def connect(sid, environ):
    print(f"Sensor connected: {sid}")
    print(f"Welcome, Sensor {sid}")


@sio.event
def sensor_data(sid, data):
    print(f"Data from sensor {sid}: {data}")

    processed_data = process_sensor_data(data)
    try:
        sio.emit('server_response', f'Reply from server to {sid} : {processed_data}')
    except Exception as e:
        print(f"Error sending data to {sid}: {e}")


@sio.event
def disconnect(sid):
    print(f"Sensor disconnected: {sid}")


def process_sensor_data(data):
    if 'temperature' in data:
        return f"Processed temperature data: {data['temperature']} °C"
    elif 'humidity' in data:
        return f"Processed humidity data: {data['humidity']} %"
    else:
        return "Unknown sensor type"


if __name__ == '__main__':
    import eventlet

    print("Server started")
    eventlet.wsgi.server(eventlet.listen(('0.0.0.0', 5000)), app)

client.py

import time
import socketio
import random

sio = socketio.Client()


@sio.event
def connect():
    print("Connected to server")

    while True:
        temperature_data = {
            'temperature': round(random.uniform(20, 30), 2)
        }

        sio.emit('sensor_data', temperature_data)

        time.sleep(20)


@sio.event
def server_response(data):
    print(f'Message from the server: {data}')


@sio.event
def disconnect():
    print("Disconnected from server")


sio.connect('http://<Server-ip>:5000', transports=['websocket', 'polling'])

input("Press Enter to exit...\n")

sio.disconnect()

The server.py is in the ec2 instance where it is running and when i try to connect server and client it establishes the connection and starts communicating but once i stop the client and when i rerun the client again it is giving the same error i.e sometimes(i mean every 5 or 10 run) i get the error below:

Error message :

raise exceptions.ConnectionError(exc.args[0]) from None socketio.exceptions.ConnectionError: Connection error
0

There are 0 answers