Jith
Jith

Reputation: 109

Getting started with Socket IO - how to get response

so I want to use Flask Socket IO to emit a message to all clients, but im not sure on the javascript side how to call get the message

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>

Pretty much, how do I get the response from socketio.emit('test response') ?

Upvotes: 0

Views: 650

Answers (1)

Rohan Asokan
Rohan Asokan

Reputation: 686

Add another socket.on() inside your script tag.

 <!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>

The socket.io calls are not necessarily sequential and hence you have as many socket.on as you need and based on what even is on the socket, the corresponding function will get triggered.

Hope it helps! Do ping me in the comments if you have any doubts still.

--EDIT--

Pointer to the docs for exact info on this.

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

Upvotes: 1

Related Questions