react native socket io with flask best practice

Viewed 28

I'm trying to implement websockets (stack -> react native for frontend, python flask FlaskSocketIO for backend), I'm able to establish a connection between the two, but in react side, I'm not able to listen to event which the backend is continously emitting to..., and I'm sure my backend is emitting to that particular event that I'm listening to in the frontend... below is the relevant code for it:

react native side:

websockets service utility file in react native:

import io from 'socket.io-client';

const SOCKET_URL = 'http://127.0.0.1:5000';

class WebSocketService {
    init = async () => {
        try {
            this.socket = io(SOCKET_URL, {
                transports: ['websocket'],
            });

            this.socket.on('connect', () => {
                console.log('connected');
            });

            this.socket.on('disconnect', () => {
                console.log('disconnected');
            });

            this.socket.on('error', () => {
                console.log('error');
            });
        } catch (error) {
            console.log('[SOCKET ERROR] FAILED TO INITIALIZE SOCKET ', error);
        }
    };

    emit(event: string, data: any) {
        this.socket.emit(event, data);
    }

    on(event: string, callback: any) {
        this.socket.on(event, callback);
    }

    removeListener(listener: string) {
        this.socket.removeListener(listener);
    }
}

export default new WebSocketService();

main screen where I wanna show logs realtime after mounting that screen.

const LogsDisplayScreen = () => {
  useEffect(() => {
        WebSocketService.init();
        WebSocketService.emit('subscribe', {d: 'subscribed to get realtime profit loss'})
    }, []);

    useEffect(() => { // not working...
        WebSocketService.on('get_pnl', (data: any) => {
            console.log('received data: ', data); // no logging here...
        })
        return () => {
            WebSocketService.removeListener('get_pnl');
        }
    }, []);
  return (...);
}

flask:

import time
from random import randrange
from flask import Flask
from flask_socketio import SocketIO, emit

app = Flask(__name__)
socketio = SocketIO(app, logger=True, cors_allowed_origins="*")

@socketio.on('connect')
def connect():
    print('Client Connected')

@socketio.on('disconnect')
def disconnect():
    print('Client disconnected')

@socketio.on('subscribe')
def subscribe(data):
    print('data received from client: ', str(data)) # data received from client:  {'d': 'subscribed to get realtime pnl'} -> received from frontend
    while True:
        emit('get_pnl', { 'pnl': randrange(10, 100) }) # this is emitting, can confirm through local server logs
        time.sleep(5)

if __name__ == '__main__':
    socketio.run(app)

I can confirm that from the backend side, socket is emitting successfully to event 'get_pnl' as I can see the server logs emitting every 5 seconds:

Client Connected
emitting event "my response" to bMMnXmIHMjWxAILpAAAJ [/]
data received from client:  {'d': 'subscribed to get realtime pnl'}
emitting event "get_pnl" to F02x-6g6QpieAAAB [/]
emitting event "get_pnl" to F02x-6g6QpieAAAB [/]
emitting event "get_pnl" to F02x-6g6QpieAAAB [/]
...

The problem is that in react side, I'm not able to listen to 'get_pnl' event, even though I can see in my server logs that the server is emitting to that event...

Also I would like to know any best practices to deal with socket connections because I have heard they become quite unstable...

Any guidance would be really appreciated!

0 Answers
Related