Prabhat Kumar
Prabhat Kumar

Reputation: 3

Flask socketio not receiving any message from javascript even after the connection is established

I am trying to get response from javascript after the connection is established between the flask and javascript.The onconnect() function is working properly but onmessage() is not.

I tried broadcast along with the emit method in javascript too but it's not working.

This is my app.py

app=Flask(__name__)
bootstrap=Bootstrap(app)
socketio=SocketIO(app)

app.config['SECRET_KEY']="MY_KEY"

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

@app.route('/home',methods=['GET','POST'])
def home():
    if(request.method=='POST'):
        data=request.form
        name=data['name']
        return render_template('message.html',name=name)
    else:
        return render_template('index.html')

@socketio.on('connect')
def onconnect():
    print("connect")

@socketio.on('message')
def onmessage(message):
    print('message')

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

and this is my javascript file

const ws =io.connect(window.location.href)

ws.on('connect', function() {
  console.log("Connection estalished")
  ws.emit("adsd",broadcast=true)
});

EDIT: There is a mistake in the javscript.

const ws =io()

This should be used for establishing the connection , not the previous method.

My Project is completed. Link for the github project

Upvotes: 0

Views: 96

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67492

First of all, only the server can broadcast, clients can only emit to the server.

Second, you are emitting an event named adsd, so you need to add a handler for that event in your server. For example:

@socketio.on('adsd')
def adsd_handler():
    print('got adsd!')

Upvotes: 1

Related Questions