flask - socketio请求头问题
本文介绍了flask - socketio请求头问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
我要在flask上实现websocket
通信, 前端使用的是socket.io
,后端使用的是flask_socketio
. 当我用socket.io
向服务器发送请求的时候发现请求头里没有websocket
内容知乎上关于websocket的回答.
我发现socket.io
的请求头是这样的
我看了一下我后台接受到的请求头也是这样的
我后台接受请求后怎么判断这个请求时http请求还是websocket。
服务器端代码
from flask import Flask, render_template, request
from flask_socketio import SocketIO
app = Flask(__name__)
app.config['SECRET_KEY'] = 'so hard'
socketio = SocketIO(app)
stores = set()
@app.route('/')
def hello_world():
print(request.headers)
return render_template('index.html')
@socketio.on('connect')
def connect():
stores.add(request)
print(request.headers)
print('clinet', len(stores))
@socketio.on('message')
def handle_message(message):
print('recive message:', message)
if __name__ == '__main__':
app.debug = False
socketio.run(app, host='0.0.0.0',port=8080)
解决方案
socket.io (其实大多 websocket 的库都有) 会尝试兼容各种浏览器,例如不支持 websocket 的自动切换成 ajax 轮询或者长链接等待。为了实现这个,通常第一个请求并不是建立 websocket,而是 client 和 server 沟通确认我们这次用什么姿势 >.< ,然后后续再根据结果来建立 websocket 链接或者是别的姿势 ( 逃 ...
这篇关于flask - socketio请求头问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文