Julia - 如何通过 WebSocket 订阅

2024-01-02

我想使用 Julia 使用 Websockets 订阅一些数据源。

例如,从linux终端,我可以成功获取如下数据:

wscat -c wss://www.bitmex.com/realtime
{"op": "subscribe", "args": ["orderBookL2_25:XBTUSD"]}

现在在朱莉娅,我找不到解决方案。我尝试了以下方法,但它使 Julia 崩溃:

using WebSockets, JSON

uri = "wss://www.bitmex.com/realtime"
json_part = "{'op': 'subscribe', 'args': ['orderBookL2_25:XBTUSD']}"

inbox = Channel{String}(10)
outbox = Channel{String}(10)

ws_task = @async WebSockets.open(uri) do ws
  while isopen(ws)
        inbox_task = @async while !eof(ws)
            put!(inbox, String(read(ws)))
        end
        outbox_task = @async while isopen(ws)
            write(ws, take!(outbox))
        end
    end
end

# here Julia is crashing (hangs forever, I cannot get the cursor back)

put!(outbox, json_part)
take!(inbox)

有人可以帮助获得一个可行的解决方案来使用 Julia 订阅数据源吗?


只需要去掉外层即可while循环即可:

julia> using WebSockets, JSON

julia> uri = "wss://www.bitmex.com/realtime"
"wss://www.bitmex.com/realtime"

julia> json_part = "{'op': 'subscribe', 'args': ['orderBookL2_25:XBTUSD']}"
"{'op': 'subscribe', 'args': ['orderBookL2_25:XBTUSD']}"

julia> inbox = Channel{String}(10)
Channel{String}(sz_max:10,sz_curr:0)

julia> outbox = Channel{String}(10)
Channel{String}(sz_max:10,sz_curr:0)

julia> ws_task = @async WebSockets.open(uri) do ws
           inbox_task = @async while !eof(ws)
               put!(inbox, String(read(ws)))
           end
           outbox_task = @async while isopen(ws)
               write(ws, take!(outbox))
           end
       end
Task (runnable) @0x00000000135b3990

julia> put!(outbox, json_part)
"{'op': 'subscribe', 'args': ['orderBookL2_25:XBTUSD']}"

julia> take!(inbox)
"{\"info\":\"Welcome to the BitMEX Realtime API.\",\"version\":\"2020-10-06T22:31:35.000Z\",\"timestamp\":\"2020-10-26T16:56:02.455Z\",\"docs\":\"https://www.bitmex.com/app/wsAPI\",\"limit\":{\"remaining\":38}}"

与外while isopen(ws)在你不断创建新的地方循环inbox/outbox_tasks。我怀疑您想在 WS 连接断开或发生其他情况时重新启动它们,但您需要以不同的方式处理该问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Julia - 如何通过 WebSocket 订阅 的相关文章

随机推荐