javascript - Using websocket with Thin -
i trying use websocket on thin server. following code attempt run clock updates time on web page every 0.1 second.
page
content of initial page rendered.- the thin server initiated
serve
,session
methods. - websocket initiated
websocket
method. tick_every
utility function calls block @ right timing every time interval given.
code:
require "rack" require "thin" require "em-websocket" page = <<_ <html> <body><div id="output"></div></body> <script> window.addeventlistener("load", init, false); function init(){ websocket = new websocket("ws://localhost:4000"); websocket.onmessage = function(evt){ document.getelementbyid("output").innerhtml = evt.data; }; } </script> <div id="output"></div> </html> _ def serve rack::handler::thin.run(rack::builder.new map("/"){run(->env{session(env)})} end, port: 3000) end def session env websocket(env["server_name"]) [200, {}, [page]] end def websocket host em.run em::websocket.run(host: host, port: 4000) |ws| ws.onopen tick_every(0.1){|t| ws.send "the time since epoch in sec #{t}"} end end end end def tick_every sec, &pr thread.new loop t = time.now.to_f # present time in micro seconds frac = t.modulo(sec.to_f) # fractional (decimal) part of w.r.t. `sec` pr.call((t - frac).round(6)) # calls block, passing present time precision of `sec` sleep(sec - frac) # wait next flat `sec` end end end serve
when run , open webpage @ localhost:3000
, websocket
returns error message in console:
!! unexpected error while processing request: no acceptor (port in use or requires root privileges)
and shows initial time on web page, not update thirty seconds (not sure, seems constant, may have meaning), , after that, starts update clock every 0.1 second.
- what causing error message websocket?
- why pause thirty seconds , start working?
- is proper way combine ajax , websocket?
- how can fix these problems?
the problem turned out that, browser requesting favicon, had not set up. probably, waited till timeout, perhaps thirty seconds, started work after that. error came favicon request.
Comments
Post a Comment