Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HTTP::WebSocket#run #5641

Closed
mxrguspxrt opened this issue Jan 25, 2018 · 1 comment · Fixed by #9761
Closed

HTTP::WebSocket#run #5641

mxrguspxrt opened this issue Jan 25, 2018 · 1 comment · Fixed by #9761
Labels
community:to-document good first issue This is an issue suited for newcomers to become aquianted with working on the codebase. kind:docs

Comments

@mxrguspxrt
Copy link

mxrguspxrt commented Jan 25, 2018

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

@ysbaddaden
Copy link
Contributor

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

@jhass jhass added good first issue This is an issue suited for newcomers to become aquianted with working on the codebase. community:to-document kind:docs labels Jul 22, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
community:to-document good first issue This is an issue suited for newcomers to become aquianted with working on the codebase. kind:docs
Projects
None yet
3 participants