miguelgrinberg / Flask-SocketIO

Socket.IO integration for Flask applications.
MIT License
5.37k stars 893 forks source link

socketio emit not working in the loop #1774

Closed ghost closed 2 years ago

ghost commented 2 years ago

Hi, I am trying to broadcast every 5 seconds from a server.py to a client in angular, information inside a loop and from what I have read my code should work, or there is some bug I am not seeing, it stays inside the loop but the socket does not broadcast anything, I am using the latest versions of all the packages for python 3.7.4. If I remove the while:True and the socketio.sleep it works correctly.

Server Code:

from pycoingecko import CoinGeckoAPI
from flask_cors import CORS
from flask_socketio import SocketIO
from flask import Flask
from threading import Thread
import time
import json
from gevent import monkey
monkey.patch_all()

CoinGeckoClient = CoinGeckoAPI()
app = Flask(__name__)
app.config['SECRET_KEY'] = 'vnkdjnfjknfl1232#'
socketio = SocketIO(app, cors_allowed_origins="*")
CORS(app)
thread = None

def background_stuff():
    while True:
        time.sleep(5)
        allDataBTC = CoinGeckoClient.get_coin_market_chart_by_id(
            id='bitcoin', vs_currency='eur', days='1')
        allDataETH = CoinGeckoClient.get_coin_market_chart_by_id(
            id='ethereum', vs_currency='eur', days='1')

        s1 = json.dumps(allDataBTC)
        s2 = json.dumps(allDataETH)
        allDataBTCJSON = json.loads(s1)
        allDataETHJSON = json.loads(s2)
        print("Entrando a get prices")
        pricesBTC = allDataBTCJSON["prices"]
        pricesETC = allDataETHJSON["prices"]
        socketio.emit('push', {
            'data': [
                {'name': 'BTC', 'prices': pricesBTC},
                {'name': 'ETH', 'prices': pricesETC}
            ]

        })

@socketio.on('connect')
def connect():
    global thread
    if thread is None:
        thread = Thread(target=background_stuff)
        thread.start()

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

Client node js:

const io = require("socket.io-client");
const socket = io("http://localhost:5000");
socket.on("connect", () => {
    console.log(socket.id); 
  });
socket.on("push", (data) => {
    console.log("data llegó");
    console.log(data); 
});

The client does not even receive the connection and therefore does not print console.log('Conectado'). I would be immensely grateful for help.

miguelgrinberg commented 2 years ago

Try moving the monkey patching code to the very top of the file, above all other imports. Also, please don't write bugs against this package when you have a question about your own code. There is a discussion board for quesitons.