如何在WebSocket Python客户端中添加更多头部 [英] How to add more headers in websocket python client

查看:25
本文介绍了如何在WebSocket Python客户端中添加更多头部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过WebSocket连接(我使用的是Python WebSocket客户端)发送会话ID(在对http服务器进行身份验证后获得),我需要将其作为Header参数传递,其中服务器(Tornado WebSocket服务器)将读取所有标头并对其进行检查。

问题是:我如何使用现有的客户端Python WebSocket实现之一添加标头,我发现它们都不能做到这一点,或者我一开始就遵循了错误的身份验证方法?

--更新--,下面是我使用的代码模板:

def on_message(ws, message):
    print 'message received ..'
    print message


def on_error(ws, error):
    print 'error happened .. '
    print error


def on_close(ws):
    print "### closed ###"


def on_open(ws):

    print 'Opening Websocket connection to the server ... '

    ## This session_key I got, need to be passed over websocket header isntad of ws.send.
    ws.send(session_key)

if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://localhost:9999/track",
                                on_open = on_open,
                                on_message = on_message,
                                on_error = on_error,
                                on_close = on_close, 
                                )
    ws.on_open = on_open

    ws.run_forever()

推荐答案

自从提出此问题以来,WebSocket-Client似乎已更新为包括WebSocket标头。现在,您只需将标头参数列表作为字符串传递即可:

custom_protocol = "your_protocol_here"
protocol_str = "Sec-WebSocket-Protocol: " + custom_protocol
ws = websocket.WebSocketApp("ws://localhost:9999/track",
                            on_open = on_open,
                            on_message = on_message,
                            on_error = on_error,
                            on_close = on_close, 
                            header = [protocol_str]
                            )

如果您对有效标头的完整列表感兴趣,请参阅WebSocket RFC6455文档:https://www.rfc-editor.org/rfc/rfc6455#section-4.3

GitHub来源:https://github.com/liris/websocket-client/blob/master/websocket.py

这篇关于如何在WebSocket Python客户端中添加更多头部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆