朱莉娅-如何通过WebSockets订阅 [英] Julia - how to subscribe via WebSockets

查看:42
本文介绍了朱莉娅-如何通过WebSockets订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Julia使用Websocket订阅一些数据提要.

I would like to subscribe to some data feed using Websockets using Julia.

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

For example, from the linux terminal, I can successfully get data like this:

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

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

Now in Julia, I cannot find a solution. I have tried the following, but it crashes 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订阅数据供稿吗?

Can someone help to get a working solution to subscribe to data feed using Julia?

推荐答案

只需除去外部while循环,您就可以开始了:

Just remove the outer while loop and you're good to go:

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_task.我怀疑如果WS连接断开或其他原因,您想重新启动它们,但是您需要以不同的方式进行处理.

With the outer while isopen(ws) loop in place you're continously creating new inbox/outbox_tasks. I suspect you wanted to restart them if the WS connection drops or something, but you'll need to handle that differently.

这篇关于朱莉娅-如何通过WebSockets订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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