Home > front end >  How can I send a message from server to client using socketIO?
How can I send a message from server to client using socketIO?

Time:01-03

I want to send a message from server app to the html page. So, I wrote the following code.

However, the html page is showing nothing.

What am I doing incorrectly?

server_sends_client_receives.py

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

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


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


@socketio.on('my_event')
def handle_my_custom_event(data):
    emit('my_response', {data: 'sent'})


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

server_sends_client_receives.html

<!--client sends, server receives-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE E7Qv1j DyZwA==" crossorigin="anonymous"></script>
    <script type="text/javascript" charset="utf-8">
        socket.on('my_event', function (msg, cb)
        {
            $('#messages').text(msg.data).html());
            if (cb)
                cb();
        });
    </script>
</head>
<body>
<div id="messages"></div>
</body>
</html>

CodePudding user response:

Your client page does not establish a socket connection. Try as follows:

<script type="text/javascript" charset="utf-8">
    var socket = io();
    socket.on('connect', function() {
        socket.emit('my event', {data: 'I\'m connected!'});
    });
</script> 

CodePudding user response:

Flask is a synchronous framework. I had no success running another asynchronous socket thread on top of it's own. Consider instead using another server opened at the same time with an asynchronous framework like aiohttp. I had great success combining Django's synchronous database with aiohttp's server socketio. In Django, there's a thing called Django Channels which also supposedly works, maybe there's something like this for Flask.

  • Related