最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】如何利用Flask-Sockets实现websocket的地址中带参数

Flask crifan 6279浏览 0评论

折腾:

【已解决】使用Flask-Sockets去实现Flask中的Websocket

之后,继续去:

那接着再去想办法实现:

如何实现类似于:

ws://jiandao.im:8080/message/{userid}/{token}

这种的地址

以便于:

针对于每个不同的用户,就实现一个ws连接:

Flask-Sockets connect disconnet

Flask-Sockets url parameter

python – How to use Flask-Sockets? Getting a KeyError: ‘wsgi.websocket’ – Stack Overflow

RFC 6455 – The WebSocket Protocol

About HTML5 WebSocket – Powered by Kaazing

Introducing Flask-Sockets — Kenneth Reitz

Lawouach/WebSocket-for-Python: WebSocket client and server library for Python 2 and 3 as well as PyPy (ws4py 0.3.5)

-》

ws4py – A WebSocket package for Python — ws4py 0.3.5 documentation

Using WebSockets on Heroku with Python | Heroku Dev Center

搜:

flask app route parameters

去参考Flask的app的route中带参数的写法

Quickstart — Flask Documentation (0.11)

然后去用:

# @sockets.route(‘/echo’)
@sockets.route(‘/users/<userId>/<accesstoken>’)
def echo_socket(ws, userId, accesstoken):
    gLog.debug("ws=%s", ws)
    gLog.debug("userId=%s, accesstoken=%s", userId, accesstoken)
    while not ws.closed:
        message = ws.receive()
        ws.send(message)

实现了对应的效果:

可以被正常打开并接受参数:

log是:

DEBUG in app [/root/RunningFast/staging/runningfast/app.py:226]:
ws=<geventwebsocket.websocket.WebSocket object at 0x7f1f997fade0>
DEBUG in app [/root/RunningFast/staging/runningfast/app.py:228]:
userId=user1, accesstoken=token2

【总结】

此处,想要获得websocket的传入的参数的话,则可以直接参考Flask的route中传入参数的的写法:

@sockets.route(‘/users/<userId>/<accesstoken>’)
def echo_socket(ws, userId, accesstoken):
    gLog.debug("ws=%s", ws)
    gLog.debug("userId=%s, accesstoken=%s", userId, accesstoken)
    while not ws.closed:
        message = ws.receive()
        ws.send(message)

然后去访问:

ws://115.29.173.126:21085/users/user5/token6

即可获得对应的参数:

userId=user5, accesstoken=token6

【后续】

【未解决】Flask-Sockets中实现对于websocket的连接的监听打开open,关闭close,发送信息messge

转载请注明:在路上 » 【已解决】如何利用Flask-Sockets实现websocket的地址中带参数

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.249 seconds, using 22.10MB memory