Flask WebSocket Messages not emitted

I want to use a WebSocket to stream dummy data (a random 4-char string) to a div on a HTML page, using Python with the Flask webserver. The source for both Python and HTML follows.

main7.py

from flask import Flask, render_template
from flask_socketio import SocketIO
import random
import string

app = Flask(__name__)
socketio = SocketIO(app)

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

def generate_random_chars():
    while True:
        random_chars = ''.join(random.choices(string.ascii_letters + string.digits, k=4))
        socketio.emit('update', random_chars)
        socketio.sleep(2)

if __name__ == '__main__':
    socketio.start_background_task(target=generate_random_chars)
    socketio.run(app, host='localhost', port=5000, debug=True)

index7.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flask WebSocket Test</title>
</head>
<body>
    <div id="random-chars">Waiting for updates...</div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.js"></script>
    <script>
        const socket = io();
        socket.on('update', function(data) {
            document.getElementById('random-chars').innerText = data;
        });
    </script>
</body>
</html>

The page is served with no error and there appears to be a WebSocket connection established but after that, there none of the emitted messages appear in the network traffic.
There are also no error messages from the Flask debug output, or the DevTools console.

 * Restarting with watchdog (inotify)
 * Debugger is active!
 * Debugger PIN: 136-937-281
(210008) wsgi starting up on http://127.0.0.1:5000
(210008) accepted ('127.0.0.1', 49994)
127.0.0.1 - - [29/Aug/2024 19:48:45] "GET / HTTP/1.1" 200 640 0.003211
(210008) accepted ('127.0.0.1', 49998)
127.0.0.1 - - [29/Aug/2024 19:48:45] "GET / HTTP/1.1" 400 293 0.001261
127.0.0.1 - - [29/Aug/2024 19:49:04] "GET / HTTP/1.1" 200 611 0.002471
127.0.0.1 - - [29/Aug/2024 19:49:04] "GET /socket.io/?EIO=4&transport=polling&t=P6V2cR7 HTTP/1.1" 200 278 0.000470
(210008) accepted ('127.0.0.1', 42628)
(210008) accepted ('127.0.0.1', 42634)
127.0.0.1 - - [29/Aug/2024 19:49:04] "POST /socket.io/?EIO=4&transport=polling&t=P6V2cRC&sid=WyHUScU-T8s22PT_AAAA HTTP/1.1" 200 219 0.001391
127.0.0.1 - - [29/Aug/2024 19:49:04] "GET /socket.io/?EIO=4&transport=polling&t=P6V2cRD&sid=WyHUScU-T8s22PT_AAAA HTTP/1.1" 200 213 0.000228
127.0.0.1 - - [29/Aug/2024 19:49:04] "GET /socket.io/?EIO=4&transport=polling&t=P6V2cRM&sid=WyHUScU-T8s22PT_AAAA HTTP/1.1" 200 181 0.000252
127.0.0.1 - - [29/Aug/2024 19:49:48] "GET /socket.io/?EIO=4&transport=websocket&sid=WyHUScU-T8s22PT_AAAA HTTP/1.1" 200 0 43.720072
127.0.0.1 - - [29/Aug/2024 19:49:48] "GET / HTTP/1.1" 200 611 0.001028
127.0.0.1 - - [29/Aug/2024 19:49:48] "GET /socket.io/?...

Any insight into the problem appreciated!

2

The solution was to avoid the race conditions pointed out by user Woodford, in particular to start the emit task only after the WebSocket connection is established.
Below is the modified working code with extra network status reporting on the client side:

main.py

from datetime import datetime
import logging
from flask import Flask, render_template
from flask_socketio import SocketIO

app = Flask(__name__)
socketio = SocketIO(app)

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

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

def generate_time_str():
    while True:
        time_str = str(datetime.now())
        logger.info(f"Emitting: {time_str}")
        socketio.emit('update', time_str)
        socketio.sleep(1)

@socketio.on('connect')
def handle_connect():
    logger.info("Client connected")
    socketio.start_background_task(target=generate_time_str)

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

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flask WebSocket Test</title>
    <style>
        .error { color: red; }
        .connected { color: green; }
        .disconnected { color: orange; }
    </style>
</head>
<body>
    <div id="server-data"></div>
    <div id="network-status">Connecting to server...</div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const socket = io({
                reconnection: true,
                reconnectionAttempts: Infinity,
                reconnectionDelay: 1000,
                reconnectionDelayMax: 5000,
                timeout: 20000,
            });
            const randomCharsDiv = document.getElementById('server-data');
            const networkStatusDiv = document.getElementById('network-status');
            
            function updateNetworkStatus(message, className) {
                networkStatusDiv.textContent = message;
                networkStatusDiv.className = className;
            }

            socket.on('connect', function() {
                console.log('Connected to server');
                updateNetworkStatus('Connected to server', 'connected');
            });

            socket.on('update', function(data) {
                console.log('Received update:', data);
                randomCharsDiv.textContent = data;
            });

            socket.on('disconnect', function(reason) {
                console.log('Disconnected from server:', reason);
                updateNetworkStatus('Disconnected from server', 'disconnected');
            });

            socket.on('connect_error', function(error) {
                console.error('Connection error:', error);
                updateNetworkStatus('Error connecting to server', 'error');
            });

            socket.on('reconnect_attempt', function(attemptNumber) {
                console.log('Attempting to reconnect:', attemptNumber);
                updateNetworkStatus(`Attempting to reconnect (${attemptNumber})`, 'disconnected');
            });

            socket.on('reconnect', function(attemptNumber) {
                console.log('Reconnected on attempt:', attemptNumber);
                updateNetworkStatus('Reconnected to server', 'connected');
            });

            socket.on('reconnect_error', function(error) {
                console.error('Reconnection error:', error);
                updateNetworkStatus('Error reconnecting to server', 'error');
            });

            socket.on('reconnect_failed', function() {
                console.error('Failed to reconnect');
                updateNetworkStatus('Failed to reconnect to server', 'error');
            });
        });
    </script>
</body>
</html>

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật