如何在WebSocket Python客户端中添加更多头部

2022-04-15 00:00:00 python websocket tornado

问题描述

我正在尝试通过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

相关文章