Yousef Haggy
Yousef Haggy

Reputation: 43

Python Flask-socketio working, not receiving data from JS client

I am trying to setup a basic web socket using flask-socketio and the javascript socket-io library on the front end. The frontend successful registers the connection. However, in the python console, my log messages are not working and there is no indication that the server is responding to my requests.

All I get in the console on connect is: "GET /socket.io/?EIO=3&transport=polling&t=MJHl5WD HTTP/1.1" 200 - 127.0.0.1 - - [25/Jul/2018 09:58:58] "POST /socket.io/?EIO=3&transport=polling&t=MJHl5WQ&sid=b2a1f92c18e349c5a11df25e5001766c HTTP/1.1" 200 -

So the connection is working, however, nothing else on the back end is outputting as it should.

Here is the JS:

var socket=io('http://127.0.0.1:5000');
socket.on('connect',function(){
    console.log("connected");
socket.emit('client_connected',{data:"testsend"});

});
socket.on('update',function(data){
console.log(data)
});

And the python:

import json
import urllib3
from bs4 import BeautifulSoup
from flask import Flask, jsonify, render_template, request
from flask_socketio import SocketIO, send, emit

app=Flask(__name__)
socketio= SocketIO(app)
if __name__ == '__main__':
    socketio.run(app)
socketio.emit('update',{'data':"test"});

@socketio.on('client_connected')
def handle_client_connect_event(data):
    print("connected")
    print(str(data))    
@socketio.on('disconnect')
def disconnected():
    print('disconnected')
@socketio.on('connect')
def connected():
    print('connected')

None of the @socketio.on lines work, and the 'update' event isn't working either. Help would be greatly appreciated.

Upvotes: 4

Views: 3452

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67492

The event definitions are below the socketio.run(), which starts the server and blocks, so they never get registered. If you move those above this call they should just work.

Upvotes: 3

Related Questions