You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask SocketIO实现客户端多请求同时更新问题求助

Fixing Concurrent Real-Time Updates in Flask-SocketIO Dashboard

Hey there! Let's get your two data streams updating simultaneously. The issues are small but critical in your client-side code, plus we'll confirm the server setup is correct.

Key Issues in Original Code

  • Undefined socket2 variable: You tried listening for temp2 events on socket2, but this socket instance never existed. Socket.IO uses a single connection for all events—you don't need multiple socket objects.
  • Untriggered check2 event: Your client only sent the check event on connect, so the server's gen2 function never started running.
  • Server side reminder: Using socketio.sleep() (instead of time.sleep()) is correct here—it's non-blocking, allowing both handlers to run concurrently.

Corrected Code

app.py (No Changes Needed!)

Your server code is already set up correctly. The socketio.sleep() calls ensure that neither infinite loop blocks the other.

from flask import Flask, render_template
from flask_socketio import SocketIO

app = Flask(__name__)
socketio = SocketIO(app, logger=True, engineio_logger=True)

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('check')
def gen(data):
    j=0
    while True:
        socketio.emit('temp', data={'value1':j})
        j+=1
        socketio.sleep(0)

@socketio.on('check2')
def gen2(data):
    j= 10
    while True:
        socketio.emit('temp2', data={'value2':j})
        j+=1
        socketio.sleep(3)

if __name__== "__main__":
    socketio.run(app,debug=True, host='127.0.0.1', port=5000) 

Corrected index.html

Here's the fixed client code with key changes highlighted:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>websocket</title>
</head>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
     var socket = io.connect('http://' + document.domain + ':' + location.port);

   socket.on('connect' ,function()
     {
      socket.emit('check' ,{data: 'User Connected'});
      // Added: Trigger the second data stream
      socket.emit('check2' ,{data: 'User Connected'});
     });

    socket.on('temp' ,function(msg) 
    {
        console.log(msg.value1)
        $('#test').html('<p> Value 1: ' + msg.value1 + '</p>');
     });
     // Fixed: Use the existing socket instance instead of socket2
     socket.on('temp2' ,function(msg) 
     {
        console.log(msg.value2)
        $('#test2').html('<p> Value 2: ' + msg.value2 + '</p>');
     });
    });

 </script>
 <p id='test'> Hello </p>
 <br/><br/>
 <p id='test2'> Hello </p>

</body>
</html>

What Changed?

  1. Emitted both events on connect: We added socket.emit('check2') so the server starts sending both data streams.
  2. Used a single socket instance: Removed the non-existent socket2 variable and used the same socket to listen for both temp and temp2 events.

Setup Note

Make sure you have eventlet installed (the default concurrency backend for Flask-SocketIO) with:

pip install eventlet

Once you run the app, you'll see Value 1 update instantly and Value 2 update every 3 seconds—both running simultaneously!

内容的提问来源于stack exchange,提问作者Athul R T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 17:20:19