python - 如何在 websocket python 客户端中添加更多 header

标签 python websocket

我正在尝试通过 websocket 连接(我正在使用 python websocket 客户端)发送 session ID(我在对 http 服务器进行身份验证后获得它),我需要将其作为 header 传递参数,服务器将在其中读取所有 header 并检查它们。

问题是:如何使用现有的客户端 python Websocket 实现添加 header ,我发现它们都不能这样做,还是我一开始就采用了错误的方法进行身份验证?

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

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 header ,因为这个问题被问到。现在您可以简单地将 header 参数列表作为字符串传递:

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]
                            )

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

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

关于python - 如何在 websocket python 客户端中添加更多 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14454949/

相关文章:

python - 使用 tensorflow 一次切片多个切片

java - Spring +WebSocket+STOMP。给特定 session 的消息(不是用户)

c - C 中的 Websocket 实现

java - Spring Websocket ChannelInterceptor 未触发 CONNECT 事件

python - 尝试创建 pandas 数据框时出现错误 ' No objects to concatenate'?

python - 使用多处理获取数据

javascript - 连接两个动态创建的选择元素

python - 为什么 Anaconda 有两个相同的 `libpython2.7.so` ?

python - Websocket 在 Tornado 中收到响应后持续监听

node.js - 获取http ://localhost:8080/socket. io/?EIO=3&transport=polling&t=McNiz_D 404(未找到)