I'm trying to incorporate socketio with my flask project. Right now I am trying to get a simple "Connected" or "Disconnected" output from the server. However when I run the app script with "python app.py" I don't get these messages nor any errors pointing me in any direction.
I never thought I would miss errors!
app.py
from flask import Flask, render_template, request, url_for, copy_current_request_context
from flask_socketio import SocketIO, emit
import logging
logging.basicConfig()
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True
socketio = SocketIO(app)
@app.route('/scan/')
def waitForRFID():
return render_template('scan.html')
@socketio.on('connect', namespace='/test')
def test_connect():
print('Client connected')
@socketio.on('disconnect', namespace='/test')
def test_disconnect():
print('Client disconnected')
if __name__ == '__main__':
socketio.run(app)
scan.html
<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
<script src="{{ url_for('static', filename = 'js/scan.js') }}"></script>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='css/scan.css') }}" />
</head>
scan.js
$(document).ready(function(){
//connect to the socket server.
var socket = io.connect('http://' + document.domain + ':' + location.port + '/test');
});
When I run the app.py file and visit "127.0.0.1:5000/scan/", I get the following output in terminal:
127.0.0.1 - - [2018-02-11 16:42:10] "GET /scan/ HTTP/1.1" 200 812 0.010323
The web-page loads properly, and I get the same output if I run this in or out of a virtual environment.
With a setup as simple as this, what could be wrong? Thank you in advance!
In trying to reproduce your problem with the setup given, I noticed the following error in the Javascript console:
Your example doesn't have jQuery loaded, so your scan.js isn't able to connect to the socket when the document is finished loading.
You can add jQuery by including the CDN reference below:
And then we see the example works: