2016-08-12 45 views
2

我是水晶初學者。 我有問題,也許有人可以幫助我。水晶郎光纖和網絡插座

我使用凱末爾框架。 有這樣的代碼:

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 

但結果發送到網絡插座只有一次。

(僅在第一次發佈後請求)

我該如何解決?

回答

2

我不是凱馬爾專家,我不知道你想要的行爲是什麼,但是如果你想每次有人發帖子給「/ posts」發送websocket消息,我會做一個循環:

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

否則,我假定websocket連接在塊完成時關閉 – asterite