schumi
schumi

Reputation: 21

Crystal lang fiber and web socket

I'm beginner in crystal. I have question, maybe somebody can help me.

I use Kemal framework. Have this code:

require "kemal"
require "json"

channel = Channel(Card).new

post "/posts" do |env|
  json = JSON.parse(env.request.body as String)

  url = json["url"].to_s

  spawn do
    # Slow process
    page = Scraper.new(url)
    channel.send(page)
  end

  {"url" => url}.to_json
end

ws "/" do |socket|
  data = channel.receive
  socket.send data.to_h.to_json
end

Kemal.run

But the result is sent to web socket only once.

(Only after first post request)

How can I fix it?

Upvotes: 2

Views: 705

Answers (1)

asterite
asterite

Reputation: 2926

I'm not a kemal expert, and I don't know what's your intended behaviour, but if you want to send the websocket a message each time someone posts to "/posts", I would make a loop:

while data = channel.receive?
  socket.send(data.to_h.to_json)
end

Upvotes: 2

Related Questions