Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you send messages from Flask server (Python) to HTML client?

For practice, I'm trying to get the Flask server to constantly print "Hello" to the HTML page's console. I'm currently lost with how to proceed.

Currently, my server code looks something like this

app = Flask(__name__)
 app.config['SECRET_KEY'] = 'secret!'
 socketio = SocketIO(app)

@socketio.on('message')
 def handle_message(message):
    print('Message: ' + message)
     send(message)

@socketio.on('json')
 def handle_json(json):
    send(json, json=True)

@socketio.on('my event')
  def handle_my_custom_event(json):
     emit('my response', json, broadcast=True)

def hello():
    emit('message', {'hello':"Hello"})

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

if __name__ == '__main__':
     socketio.run(app)
     while True:
          hello()

While my client code looks like this:

<head>
      <script type="text/javascript" charset="utf-8">
            var socket = io.connect('http://' + document.domain + ':' + location.port);
            socket.on('connect', function() {
                 socket.emit('connected');
            });
            socket.on('message', function(data) {
                 console.log(data);
            });
      </script>
</head>

But I'm not getting anything in my console log for the page. How do I get it to print the message sent from the Flask server to the console? What am I doing wrong?

I understand right now, it should print the JSON instead of the "Hello" string, and that's ok too. I just want something to print on the web console from the server.

like image 442
Jon Avatar asked Dec 24 '22 19:12

Jon


1 Answers

Here's a simple example showing how to connect to the SocketIO server and receive a message from the server upon that connection.

app.py

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

app = Flask(__name__)                                                           
app.config['SECRET_KEY'] = 'secret!'                                            
socketio = SocketIO(app)                                                        


@socketio.on('connect')                                                         
def connect():                                                                  
    emit('message', {'hello': "Hello"})                                         


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


if __name__ == '__main__':                                                      
    socketio.run(app, debug=True) 

templates/index.html

<head>

      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
      <script type="text/javascript" charset="utf-8">
            var socket = io.connect('http://' + document.domain + ':' + location.port);
            socket.on('connect', function() {
                 console.log('connected');
            });
            socket.on('message', function(data) {
                 console.log(data);
            });
      </script>
</head>

Edit:

To have the server send a socketio message every five seconds, you can use a background thread:

app.py

from flask import Flask, render_template                                        
from flask_socketio import SocketIO, emit                                       
import time                                                                     

app = Flask(__name__)                                                           
app.config['SECRET_KEY'] = 'secret!'                                            
socketio = SocketIO(app)                                                        
thread = None                                                                   


def background_thread():                                                        
    while True:                                                                 
        socketio.emit('message', {'goodbye': "Goodbye"})                        
        time.sleep(5)                                                           


@socketio.on('connect')                                                         
def connect():                                                                  
    global thread                                                               
    if thread is None:                                                          
        thread = socketio.start_background_task(target=background_thread)       


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


if __name__ == '__main__':                                                      
    socketio.run(app, debug=True)
like image 190
Matt Healy Avatar answered Dec 28 '22 09:12

Matt Healy