0

I read in Flask documentation (https://flask-socketio.readthedocs.io/en/latest/#broadcasting) that emitting a message to a client can be triggered by an event that originated in the server. So I decided to try that out. The idea is that client sends number 15 to server every second and the server, regardless of what client is doing, sends number 12 to client every two seconds.

Server side (.py):

from flask import Flask, jsonify, request, render_template
from flask_socketio import SocketIO, emit

app = Flask(__name__, static_folder='')
io = SocketIO(app, cors_allowed_origins="*")

@io.on('connected')
def connected():
    print("client connected")

@io.on('messageC')
def messageC(data):
    print(data)

def send_messageS():
    io.emit('messageS', 12)

if __name__ == '__main__':
    import _thread, time
    _thread.start_new_thread(lambda: io.run(app), ())

   while True:
       time.sleep(2)
       send_messageS()

client side (.html):

<html>
<body>

    <script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
    <script type="text/javascript" src="/resources/socket.io.js"></script>
    <script type="text/javascript" charset="utf-8">
        $(document).ready(function(){

           var socket = io.connect('http://localhost:5000');
           socket.on('connect', function() {
              socket.emit('connected');
           });

           socket.on('messageS', function(data) {
              console.log(data);
           });

           setInterval(function() { 
              socket.emit('messageC', 15);
           },1000);

        });
    </script>

</body>

The result is that number 15 is received by the server every second is desired, but number 12 is never received by the client.

What am I doing wrong?

Lucy865
  • 15
  • 6
  • are you sure the client connects? Do you get "client connected" in your log? Also check the Developer Console in your browser for errors on the Javascript side – Cfreak Oct 16 '19 at 17:01
  • Yes, I do get "client connected" and there is nothing in the browser's console. I just noticed I mistook 12 for 15 in my question, now it's corrected, so please read it again if you can. Number 15 emitted by client is received by server. But number 12 emitted by server is not received by client. – Lucy865 Oct 16 '19 at 18:59

1 Answers1

0

I found a solution. Apparently eventlet does not work with Python threads. So the solution is to "monkey patch the Python standard library so that threading, sockets, etc. are replaced with eventlet friendly versions."

    import eventlet
    eventlet.monkey_patch()

This did the trick for me. I found this solution here: How to send message from server to client using Flask-Socket IO

Lucy865
  • 15
  • 6