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)
阅读 8.7k
4 个回答

socket.io (其实大多 websocket 的库都有) 会尝试兼容各种浏览器,例如不支持 websocket 的自动切换成 ajax 轮询或者长链接等待。为了实现这个,通常第一个请求并不是建立 websocket,而是 client 和 server 沟通确认我们这次用什么姿势 >.< ,然后后续再根据结果来建立 websocket 链接或者是别的姿势 ( 逃 ...

前几天刚学完websocket的,我不太懂Python,我是用PHP的,但实现原理应该是一样的。
我说下我的实现流程吧:
首先你要让Websocket服务端启动起来啊,就差不多是让启动一个WebSocket服务器,windows是用cmd运行服务端.php文件,让服务器一直处于挂起状态。
服务端.php(大概长这样):
大概长这样

cmd运行界面(需要一直挂起):
图片描述

然后前端是用JS实例化HTML5提供的WebSocket API,连接上 Websocket”服务器“
大概长这样:
图片描述

heder请求与响应头是这样:
图片描述

由于你描述的不清楚所以我不知道你的问题出在哪里,你可以考虑把代码贴上来。

(我猜测你是Websocket”服务器“没启动)

服务端需要安装eventlet或者gevent才能支持websocket.

eventlet is the best performant option, with support for long-polling
and WebSocket transports.

gevent is supported in a number of different configurations. The
long-polling transport is fully supported with the gevent package, but
unlike eventlet, gevent does not have native WebSocket support. To add
support for WebSocket there are currently two options. The
gevent-websocket package adds WebSocket support to gevent, but
unfortunately this package is current only available for Python 2. The
other alternative is to use the uWSGI web server, which comes with
WebSocket functionality. The use of gevent is also a performant
option, but slightly lower than eventlet.

The Flask development server based on Werkzeug can be used as well,
with the caveat that it lacks the performance of the other two
options, so it should only be used to simplify the development

  1. This option only supports the long-polling transport.

新手上路,请多包涵

您好,想问一下,第一张图片,在请求头中,怎么加入cookie的呢?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进