Socket IO 入门 - 如何获得响应

Getting started with Socket IO - how to get response

所以我想使用 Flask Socket IO 向所有客户端发送消息,但我不确定 javascript 端如何调用获取消息

from flask import Flask, render_template
from flask_socketio import SocketIO

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

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

@socketio.on('test')
def test():
    print('test my event')
    socketio.emit('test response')

if __name__ == '__main__':
    socketio.run(app, debug=True)
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <title>Test</title>
  </head>
  <body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.4/socket.io.js" integrity="sha512-aMGMvNYu8Ue4G+fHa359jcPb1u+ytAF+P2SCb+PxrjCdO3n3ZTxJ30zuH39rimUggmTwmh2u7wvQsDTHESnmfQ==" crossorigin="anonymous"></script>
    <script type="text/javascript">
        var socket = io.connect('http://' + document.domain + ':' + location.port);
        socket.on('connect', function() {
        socket.emit('test') }
    </script>
 

  </body>
  </html>

差不多,我如何从 socketio.emit('test response') 得到响应?

在您的脚本标签内添加另一个 socket.on()。

 <!DOCTYPE html>
  <html lang="en">
  <head>
    <title>Test</title>
  </head>
  <body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.4/socket.io.js" integrity="sha512-aMGMvNYu8Ue4G+fHa359jcPb1u+ytAF+P2SCb+PxrjCdO3n3ZTxJ30zuH39rimUggmTwmh2u7wvQsDTHESnmfQ==" crossorigin="anonymous"></script>
    <script type="text/javascript">
        var socket = io.connect('http://' + document.domain + ':' + location.port);
        socket.on('connect', function() {
        socket.emit('test') }

        socket.on("test response", (response) => {
            console.log(response);
        });
    </script>
 

  </body>
  </html>

socket.io 调用不一定是连续的,因此您可以根据需要调用任意多个 socket.on,并且根据套接字上什至是什么,将触发相应的函数。

希望对您有所帮助!如果您还有任何疑问,请在评论中联系我。

--编辑--

指向文档的指针以获得关于此的确切信息。

https://socket.io/docs/v3/client-api/index.html#socket-on-eventName-callback