Async WebSockets #959
-
Hello everyone, I am building a package to connect to a websocket service. Here is my understanding of the WebSockets API, the function open(handler::Function)
WebSockets.open(WEBSOCKETS_URL) do ws
global webSocket[] = ws
while true
response = receive(ws)
handler(JSON3.read(response, Response))
end
end
end
function close()
WebSockets.close(webSocket[])
end the Love your feedback, just starting out in julia. |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 2 replies
-
I'd recommend taking a look at the WebSockets documentation; particularly, we recommend this following pattern: WebSockets.open(url) do ws
for msg in ws
# do cool stuff with msg
end
end For async, you can just wrap that block with the websocket_client_task = @async WebSockets.open(url) do ws
for msg in ws
# do cool stuff with msg
end
end |
Beta Was this translation helpful? Give feedback.
-
Hello @quinnj thank you for the reply, on my way to discovering tasks and channels then. :) |
Beta Was this translation helpful? Give feedback.
-
After much learning, I still find the current API to badly embedd with Tasks when desiring bi-directional commnication. function receive(c::Channel)
WebSockets.open(url) do ws
# TODO send subscriptions
for msg in ws
# do cool stuff with msg
end
end
channel = Channel(receive) In order to pass the subscription parameters (the I'd value a feedback on the approach. Maybe I'm missing something. In any case, ❤️ |
Beta Was this translation helpful? Give feedback.
-
I don't think there is an async API to provide HTTP.WebSockets with callbacks. function create_ws(WEBSOCKETS_URL, subscriptions, callback)
return function()
WebSockets.open(WEBSOCKETS_URL) do ws
global webSocket[] = ws
# TODO send subscriptions
while true
response = receive(ws)
callback(JSON3.read(response, Response))
sleep(0.05) # sleep a little
end
end
end
end |
Beta Was this translation helpful? Give feedback.
I'd recommend taking a look at the WebSockets documentation; particularly, we recommend this following pattern:
For async, you can just wrap that block with the
@async
macro and store the task to inspect later if needed: