目前,user登录后,我返回了tokenusing JSON。随后,他们必须向该index页面发出请求,并在token中传递HTTP Authorisation header。
该index.html页面包含以下内容:
var socket = io.connect('http://' + document.domain + ':' + location.port + namespace);
socket.on('connect', function() {
socket.emit('join', {room: 'venue_1'});
});
Run Code Online (Sandbox Code Playgroud)
如果user遵循此事件过程,socket则只有在事件之后才可以连接login。但是,我试图防止有人可能只创建html包含上述代码的文件,而不先执行该login步骤的情况。
服务器代码
@socketio.on('connect', namespace='/test')
def test_connect():
# Can anything be done here to verify a user?
emit('my response', {'data': 'Connected'})
Run Code Online (Sandbox Code Playgroud)
有没有办法将a传递token给上述connect事件,以便在那里验证用户。如果token最终无效,我可以打个disconnect电话。
还是在我打以下电话时需要发生这种情况?
socket.emit('join', {room: 'venue_1', …Run Code Online (Sandbox Code Playgroud) 在我的项目中,我正在使用带有RESTful API的React前端和Flask服务器。基本功能是前端从服务器获取数据并显示它。这可以正常工作,但是我认为我可以通过使服务器每当服务器从其他地方接收到新数据时自动重新获取客户端来进行改进。我可以使用轮询并仅在一定间隔内触发获取请求,但这似乎是WebSockets的完美用例。因此,我正在尝试在服务器和客户端之间实现Websocket连接,当某些事件发生时,服务器会将消息发送到客户端。
我的服务器是用Flask用python编写的,使用特定于Flask的websocket库似乎是一个好主意。我最终使用了flask-socketio,但是在使其工作时遇到了问题。我的服务器的相关部分如下:
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
... # Server functionality for receiving and storing data from elsewhere, not related to the websocket
# Handle the webapp connecting to the websocket
@socketio.on('connect')
def test_connect():
print('someone connected to websocket')
emit('responseMessage', {'data': 'Connected! ayy'})
# Handle the webapp connecting to the websocket, including namespace for testing
@socketio.on('connect', namespace='/devices')
def test_connect2():
print('someone connected to websocket!')
emit('responseMessage', {'data': 'Connected! ayy'})
# Handle …Run Code Online (Sandbox Code Playgroud) 我有一个使用基本身份验证进行身份验证的 Flask-SocketIO 应用程序。我试图确保我的所有套接字通信也受到保护,至少达到与基本身份验证相同的程度。
\n\n来自 Flask-SocketIO 有关身份验证的文档:
\n\n\n\n\n然而,大多数情况下,在建立 SocketIO 连接之前执行传统的身份验证过程更为方便。然后可以将 user\xe2\x80\x99s 身份记录在用户会话或 cookie 中,稍后当建立 SocketIO 连接时,SocketIO 事件处理程序将可以访问该信息。
\n
因此,我试图弄清楚如何通过用户会话来安全地存储某些内容。假设我执行以下操作,首先登录,我签署了哈希用户名和密码:
\n\nfrom flask import session\nfrom itsdangerous import Signer\n\nsigner = Signer(\'super secret key\')\ndef login(username: str, password: str):\n if (username, password) in credentials:\n hashed = hash(username + password)\n session[\'user\'] = s.sign(hashed)\nRun Code Online (Sandbox Code Playgroud)\n\n然后我可以为我的 socketio 侦听器创建一个装饰器,它只需检查会话中的签名值是否有效:
\n\ndef authenticated_only(f):\n @functools.wraps(f)\n def wrapped(*args, **kwargs):\n try:\n signer.unsign(session[\'user\'])\n return f(*args, **kwargs)\n except BadSignature:\n disconnect()\n return wrapped\n\n@socketio.on(\'my event\')\n@authenticated_only\ndef handle_my_custom_event(data):\n pass\nRun Code Online (Sandbox Code Playgroud)\n\n这是一个合理的做法吗?有我遗漏的陷阱吗?这是没有意义的,因为我正在使用基本身份验证?
\n我目前正在使用Flask-SocketIO通过Internet发送内容的项目,但是遇到了这个问题。
题:
有什么办法可以在Flask-SocketIO中发送图像?我做了一些谷歌搜索,但是对我来说没有运气。
我正在使用 Flask SocketIO 这是我在服务器中的启动文件:
app = Flask(__name__)
app.config['SECRET_KEY'] = APP_SECRET_KEY
JWTManager(app)
CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
app.config['transports'] = 'websocket'
app.config['JSON_SORT_KEYS'] = False
socketio = SocketIO(app, cors_allowed_origins="*")
socketio.run(app, host=SERVER_IP, debug=True)
Run Code Online (Sandbox Code Playgroud)
我有一个简单的路由,它向客户端发出一条消息,表明其目的是触发客户端向服务器发送一段代码,该代码将允许服务器退出 while 循环并继续执行该路由。路线如下:
@app.route('/socket')
def send_socket():
socketio.emit('custom', {'data': 123})
code = ''
while not code :pass
// another logic here - after code received
Run Code Online (Sandbox Code Playgroud)
在客户端中我订阅该事件:
socket.on('custom', (data) => {
// emit the code to the server
});
Run Code Online (Sandbox Code Playgroud)
我还有一个按钮可以触发对服务器 /socket 路由的 api 请求:
const response = await axios
.get('http://serverip:5000/socket')
.catch((error: AxiosError) => { …Run Code Online (Sandbox Code Playgroud) I'm new to web sockets (specifically to socketIO interfaces, both client and server), and I wonder how basic JWT auth is usually implemented. How the headers are passed through. Should I add them to every socket listener or emit event? Or just once during the connection. Maybe the connection is already considered private because of the connection id?
I am using Socket.io-client v.4 and flask-socketio. I am interested in general practices and would be grateful for any information or your …
我正在尝试通过基本命令在 docker 中使用flask socket.io。
当我运行gunicorn的单个工作人员时,一切工作正常,但是当我增加工作人员时,然后在客户端,它开始给出400错误请求,并且在服务器日志上,我看到无效的会话lWmxdNRmai59bRfLAAAA(此错误的进一步发生将记录为级别信息)。
这些是我正在使用的命令 Gunicorn --worker-class geventwebsocket.gunicorn.workers.GeventWebSocketWorker -w 2 application:app -b 0.0.0.0:5000
和application.py文件是
from gevent import monkey monkey.patch_all()
from flask import Flask from flask_socketio import SocketIO from flask import session
app = Flask(__name__)
app.config.from_object("settings.BaseConfig")
socket_app = SocketIO(
app,
cors_allowed_origins="*",
message_queue=settings.get_evn("CACHE_QUEUE_URL"),
async_mode="gevent",
)
socket_app.init_app(app, cors_allowed_origins="*")
Run Code Online (Sandbox Code Playgroud)
我正在使用 Redis 作为消息队列,并已验证消息队列 url 是否正确
使用aws负载均衡器来处理请求
对我来说第一要点:我想实现websockets.我不需要socketIO的后备选项.
我希望"我的客户"能够实现他们想要的任何东西,只要他们遵守websockets协议.即类似于:var ws = new WebSocket.
那么..如果服务器是Flask-SocketIO,一个简单的js WebSocket会起作用吗?
ADDIONAL NOTES:Python首先!我正在尝试设置一个服务器,它只响应(实际上只发送)到websockets,没有关联的网页.(是的,我对WS很好,我不需要WSS,以防你问;)).我试着在服务器端使用烧瓶插座 https://github.com/kennethreitz/flask-sockets, 但它给了我一些问题.就像立即关闭连接和网络上的许多类似问题一样,我找不到解决方案.很难调试.所以在我开始开发新服务器之前......
flask ×5
python ×4
socket.io ×4
websocket ×3
amazon-elb ×1
gunicorn ×1
javascript ×1
python-3.x ×1
react-native ×1
reactjs ×1
sockets ×1