Crystal: HTTP::WebSocket#run

Created on 25 Jan 2018  路  1Comment  路  Source: crystal-lang/crystal

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
  1. Why run blocks all flow?
  2. It seems a bit counter intuitive that "subscribe channel" works before connection is initiated in fiber (thread)? Some clever buffering?
  3. In Ruby there is #on_open, that is quite clear DSL imho.

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

newcomer to-document docs

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:

# 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

>All comments

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
Was this page helpful?
0 / 5 - 0 ratings