[英]Using websocket with Thin
我正在嘗試在瘦服務器上使用websocket。 以下代碼是嘗試運行一個時鍾,該時鍾每0.1秒更新一次網頁上的時間。
PAGE
是要呈現的初始頁面的內容。 serve
和session
方法啟動。 websocket
方法啟動。 tick_every
是一個實用程序函數,它在給定的每個時間間隔內,在正確的時間調用一個塊。 碼:
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 do
map("/"){run(->env{session(env)})}
end, Port: 3000)
end
def session env
websocket(env["SERVER_NAME"])
[200, {}, [PAGE]]
end
def websocket host
EM.run do
EM::WebSocket.run(host: host, port: 4000) do |ws|
ws.onopen do
tick_every(0.1){|t| ws.send "The time now since epoch in sec is #{t}"}
end
end
end
end
def tick_every sec, &pr
Thread.new do loop do
t = Time.now.to_f # present time in micro seconds
frac = t.modulo(sec.to_f) # fractional (decimal) part of it w.r.t. `sec`
pr.call((t - frac).round(6)) # calls the block, passing the present time with precision of `sec`
sleep(sec - frac) # wait for the next flat `sec`
end end
end
serve
當我運行此命令並打開位於localhost:3000
的網頁時, websocket
在控制台中返回錯誤消息:
!! Unexpected error while processing request: no acceptor (port is in use or requires root privileges)
並在網頁上顯示初始時間,但不會在三十秒內更新它(不確定,但這似乎是恆定的,可能有一定含義),然后,它每0.1秒開始更新時鍾。
原來的問題是,瀏覽器正在請求一個圖標,我沒有設置它。 它可能一直等到超時(可能是三十秒),然后在那之后開始工作。 該錯誤來自網站圖標請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.