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

折腾:

【已解决】使用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



发表评论

电子邮件地址不会被公开。 必填项已用*标注

无觅相关文章插件,快速提升流量