我试图在瘦服务器上使用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秒更新一次时钟。
发布于 2013-05-21 06:28:06
问题是,浏览器请求的是一个我没有设置的图标。很可能,它一直等到超时,也就是30秒,然后才开始工作。错误来自于偏袒请求。
https://stackoverflow.com/questions/16661658
复制相似问题