Hello!
I did not find documentation about HTTP::WebSocket#run
I am not certain, am I doing it correct, but I was able to get it working as following:
external_connection = HTTP::WebSocket.new(uri)
spawn do
external_connection.run
end
external_connection.send("subscribe channel")
external_connection.on_message do |message|
puts "Received message: #{message}"
end
Could you please teach, am I doing it correctly? (I am willing to PR documentation update, but I am having trouble understanding why it works like that.)
run will put the websocket in an infinite loop, receiving messages and calling previously set callbacks, responding automatically on pings (with pongs) and of course exiting the infinite loop when the connection is closed.
For example:
# open connection
ws = WebSocket.new(uri)
# react to received messages
ws.on_message do |msg|
ws.send "response"
end
# spawn a fiber that will forward messages from a channel
spawn do
loop do
something = channel.receive
ws.send something.to_json
end
end
# start infinite loop
ws.run
Most helpful comment
run will put the websocket in an infinite loop, receiving messages and calling previously set callbacks, responding automatically on pings (with pongs) and of course exiting the infinite loop when the connection is closed.
For example: