python – 使用轮询而不是websockets的Flask-SocketIO服务器
作者:互联网
我正在研究Flask-SocketIO服务器,它运行得很好.
但是,我在服务器日志中收到了很多这样的请求:
“GET /socket.io/?EIO=3\u0026amp;transport=polling\u0026amp;t=LBS1TQt HTTP / 1.1”
这是我正在使用的代码:
from flask import Flask, render_template, redirect, url_for
from flask_socketio import SocketIO, emit
import json
def load_config():
# configuration
return json.load(open('/etc/geekdj/config.json'))
config = load_config()
geekdj = Flask(__name__)
geekdj.config["DEBUG"] = config["debug"]
geekdj.config["SECRET_KEY"] = config["secret_key"]
geekdj.config.from_envvar("FLASKR_SETTINGS", silent=True)
socketio = SocketIO(geekdj)
@geekdj.route('/')
def index():
return render_template('index.html')
# SocketIO functions
@socketio.on('connect')
def chat_connect():
print ('connected')
@socketio.on('disconnect')
def chat_disconnect():
print ("Client disconnected")
@socketio.on('broadcast')
def chat_broadcast(message):
print ("test")
emit("chat", {'data': message['data']})
if __name__ == "__main__":
socketio.run(geekdj, port=8000)
和index.html中的JS:
<script src="//cdn.socket.io/socket.io-1.4.5.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
// the socket.io documentation recommends sending an explicit package upon connection
// this is specially important when using the global namespace
var socket = io.connect('http://localhost:8000');
socket.on('connection', function(socket) {
socket.emit('foo', {foo: "bar"});
socket.join("test");
});
socket.on('joined', function(data) {
console.log('Joined room!');
console.log(data["room"]);
});
});
如果可能的话,我更愿意使用实际的Websockets,有没有人知道为什么SocketIO会回归投票?
解决方法:
我找到了解决方案in this other Q/A.
事实证明,SocketIO使用最新的连接类型设置了一个cookie.就我而言,这是民意调查.
所以,我改变了我的JS中的SocketIO连接语句
var socket = io.connect(‘http:// localhost:8000’);
至
var socket = io.connect(null,{port:8000,rememberTransport:false});
现在Chrome开发者工具中的网络选项卡下的websockets类型中有活动(之前没有):
标签:python,websocket,socket-io,flask-socketio 来源: https://codeday.me/bug/20190528/1167686.html