javascript - Server-Sent Events with Ruby Grape -
i trying create server-sent events on ruby grape api. problem connection seems closed fast time, connection closed
event time on test webpage.
the client connects server can see method being called, know why connection not constant , why don't receive data send using thread.
here ruby code:
$connections = [] class eventsapi < sinantra::base def connections $connections end "/" content_type "text/event-stream" stream(:keep_open) { |out| puts "new connection" out << "data: {}\n\n" connections << out } end post "/" data = "data\n\n" connections.each { |out| out << data } puts "sent\n" end end
here javascript:
var source = new eventsource('http://localhost:9292/events'); source.onmessage = function(e) { console.log("new message: ", e.data); showmessage(e.data); }; source.onopen = function(e) { // connection opened. }; source.onerror = function(e) { console.log("source error", e) if (e.eventphase == eventsource.closed) { console.log("connection closed"); // connection closed. } }; var showmessage = function(msg) { var out = document.getelementbyid('stream'); var d = document.createelement('div') var b = document.createelement('strong') var = new date; b.innerhtml = msg; d.innerhtml = now.gethours() + ":" + now.getminutes() + ":" +now.getseconds() + " "; d.appendchild(b); out.appendchild(d); };
edit: got working method (i changed grape::api sinatra::base grape not implement stream). receive data, connection not kept alive , when use post method data never reaches browser.
thank in advance answers.
the js code looks correct. guess should not start new thread infinite loop. happening main thread carry on executing, reach end of block, , close http request. detached thread left writing non-existent out
stream.
update in response edit: post not supported in sse. data can passed sse process using data or cookies.
Comments
Post a Comment