我正在尝试在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)
并显示网页上的初始时间,但不会更新它30秒(不确定,但这似乎不变,这可能有一些意义),然后,它开始每0.1秒更新一次时钟
答案 0 :(得分:0)
问题是,浏览器正在请求我没有设置的图标。可能它等到超时,也许是三十秒,然后开始工作。该错误来自于favicon请求。