Skip to content Skip to sidebar Skip to footer

How To Get Connected Clients In Flask

hi i need to display total number of connected clients on my flask app i write this code for checking connected and disconnected connections. app = Flask(__name__) socketio = Socke

Solution 1:

After reading a bit of socket.io documentation I've managed to spot the problems in your code.

Not a problem per-se, but incrementing/decrementing an int counter is more than enough for this use case. Secondly, you don't have to pass that counter to the render_template call as you're basically passing the user count before the conenct event has had the opportunity to fire. You should emit a message (in this example with a users topic) that will inform your page that something has changed:

from flask import Flask, request, render_template_string
from flask_socketio import SocketIO, emit

app = Flask(__name__)
socketio = SocketIO(app, logge=True)
clients = 0@socketio.on("connect", namespace="/")defconnect():
    # global variable as it needs to be sharedglobal clients
    clients += 1# emits a message with the user count anytime someone connects
    emit("users", {"user_count": clients}, broadcast=True)

@socketio.on("disconnect", namespace="/")defdisconnect():
    global clients
    clients -= 1
    emit("users", {"user_count": clients}, broadcast=True)

Moreover, you didn't open a connection to the socket in your template, this allows you to listen to the messages emitted by your socketio decorators and update all connected clients. You will also need to write a bit of javascript to specify that the counter needs to be updated anytime a user connects/disconnects.

<!-- Remember to import socketio library --><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script><script>
    $(document).ready(function(){
        var namespace = '/';    
        var socket = io.connect('http://' + document.domain + ':' + location.port + namespace);
        // Update the counter when a new user connects
        socket.on('users', function(users) {
            userCount = document.getElementById('user_counter');
            userCount.innerHTML = users.user_count;
        });
});
</script><h1id='user_counter'></h1><!-- the rest of your template -->

This being said, you don't need to pass the counter value in your render_template call. Also, from flask-socketiodocs, it seems to be good practice to start your app in the following way:

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

Here a link to an edited version of your example.

Post a Comment for "How To Get Connected Clients In Flask"