Thin サーバーで websocket を使用しようとしています。次のコードは、Web ページの時刻を 0.1 秒ごとに更新する時計を実行しようとする試みです。
PAGE
レンダリングされる最初のページのコンテンツです。- シン サーバーは メソッドで開始され
serve
ますsession
。 - Websocket は
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
これを実行して の Web ページを開くとlocalhost:3000
、websocket
コンソールに次のエラー メッセージが返されます。
!! Unexpected error while processing request: no acceptor (port is in use or requires root privileges)
Web ページに最初の時間を表示しますが、30 秒間更新しません (確かではありませんが、これは一定のようで、何らかの意味があるかもしれません)。その後、0.1 秒ごとに時計の更新を開始します。
- websocket からのエラー メッセージの原因は何ですか?
- 30 秒間停止してから動作を開始するのはなぜですか?
- これは ajax と websocket を組み合わせる適切な方法ですか?
- これらの問題を解決するにはどうすればよいですか?