2016-08-12 53 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