我正在尝试将socketio与我的烧瓶项目结合起来。现在我试图从服务器获得一个简单的“连接”或“断开连接”输出。但是,当我使用“python app.py”运行应用程序脚本时,我不会收到这些消息,也没有任何错误指向我任何方向。
我从未想过我会错过错误!
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');
});
当我运行app.py文件并访问“127.0.0.1:5000/scan/”时,我在终端中得到以下输出:
127.0.0.1 - - [2018-02-11 16:42:10] "GET /scan/ HTTP/1.1" 200 812 0.010323
网页加载正确,如果我在虚拟环境中运行,我会得到相同的输出。
如果设置简单,可能会出错?提前谢谢!
答案 0 :(得分:2)
在尝试使用给定的设置重现您的问题时,我注意到Javascript控制台中出现以下错误:
scan.js:1 Uncaught ReferenceError: $ is not defined
at scan.js:1
您的示例没有加载jQuery,因此在文档加载完成后,您的scan.js无法连接到套接字。
您可以通过在下面添加CDN参考来添加jQuery:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
然后我们看到这个例子有效:
127.0.0.1 - - [2018-02-12 07:53:58] "GET /scan/ HTTP/1.1" 200 521 0.010458
127.0.0.1 - - [2018-02-12 07:53:58] "GET /static/css/scan.css HTTP/1.1" 404 342 0.001086
127.0.0.1 - - [2018-02-12 07:53:58] "GET /static/css/scan.css HTTP/1.1" 404 342 0.000776
127.0.0.1 - - [2018-02-12 07:53:58] "GET /socket.io/?EIO=3&transport=polling&t=1518393238311-0 HTTP/1.1" 200 345 0.000879
Client connected
127.0.0.1 - - [2018-02-12 07:53:58] "POST /socket.io/?EIO=3&transport=polling&t=1518393238776-1&sid=7d98901d0ef74164975ee5464879ba19 HTTP/1.1" 200 195 0.000818
127.0.0.1 - - [2018-02-12 07:53:58] "GET /socket.io/?EIO=3&transport=polling&t=1518393238778-2&sid=7d98901d0ef74164975ee5464879ba19 HTTP/1.1" 200 198 0.000201