pragya.go
pragya.go

Reputation: 169

Web sockets in Python (using flask) issue

I am trying to build a small app to learn "web sockets with python using flask" where I am trying to count the number of user who are using the app. For that I was using Matt Makai tutorial. I guess I am messing up in something because the counter is not incrementing.

Here is my HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sockets</title>
</head>
<body>
    <h1>Welcome to sockets</h1>
    <br>
    <!--<h2> {{ counter }} visitors have seen this page!</h2>-->
    <h2><span id="user-count">0</span> visitors have seen this page! </h2>

    <script type="text/javascript"
                src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.5/socket.io.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            var url = "ws://localhost:5001";
            var socket = new io.connect(url + "/dd");
            socket.on('msg', function(msg) {
                $("#connected").html(msg.count);
            });
        });
    </script>
</body>
</html>

And this is my python code:

from gevent import monkey
monkey.patch_all()

import redis
from flask import Flask, render_template
from flask_socketio import SocketIO

app = Flask(__name__)
db = redis.StrictRedis('localhost', 6379, 0)
socketio = SocketIO(app)

@app.route('/')
def main():
    # c = db.incr('counter')
    return render_template('main.html')

@socketio.on('connect', namespace='/sockets')
def ws_conn():
    c = db.incr('user_count')
    socketio.emit('msg', {'count': c}, namespace="/sockets")

@socketio.on('disconnect', namespace='/sockets')
def ws_disconn():
    c = db.decr('user_count')
    socketio.emit('msg', {'count': c}, namespace="/sockets")


if __name__ == "__main__":              # check only if this file is called directly (not by importing somewhere else)
    socketio.run(app)

Upvotes: 1

Views: 232

Answers (1)

wmorrell
wmorrell

Reputation: 5337

You are referencing the wrong element in your HTML/Javascript.

I'm guessing you want the value in this line to update, yes?

<h2><span id="user-count">0</span> visitors have seen this page! </h2>

Yet, your Javascript code calling out to the websocket is updating an element with ID connected:

socket.on('msg', function(msg) {
    $("#connected").html(msg.count);  // <--- this line is updating the wrong thing!
});

So, you can either update the SPAN tag ID to be connected, or you can update your socket message handler to call $('#user-count').html(msg.count);.

Upvotes: 2

Related Questions