简体   繁体   English

如何使用 socketIO 从服务器向客户端发送消息?

[英]How can I send a message from server to client using socketIO?

I want to send a message from server app to the html page.我想从服务器应用程序向 html 页面发送一条消息。 So, I wrote the following code.所以,我写了下面的代码。

However, the html page is showing nothing.但是,html 页面没有显示任何内容。

What am I doing incorrectly?我做错了什么?

server_sends_client_receives.py 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 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>

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> 

Flask is a synchronous framework. Flask 是一个同步框架。 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 .考虑使用同时打开的另一台服务器和像aiohttp这样的异步框架。 I had great success combining Django's synchronous database with aiohttp's server socketio.我将 Django 的同步数据库与 aiohttp 的服务器 socketio 相结合取得了巨大的成功。 In Django, there's a thing called Django Channels which also supposedly works, maybe there's something like this for Flask.在 Django 中,有一个叫做 Django Channels 的东西据说也可以工作,也许 Flask 也有类似的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM