2013-05-21 30 views
1

我想在瘦服務器上使用websocket。下面的代碼是試圖運行一個時鐘,每0.1秒更新一次網頁上的時間。使用websocket與薄

  • PAGE是要呈現的初始頁面的內容。
  • Thin服務器以servesession方法啓動。
  • 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 

當我運行這一點,並在localhost:3000打開網頁,websocket返回在控制檯中的錯誤消息:

!! Unexpected error while processing request: no acceptor (port is in use or requires root privileges) 

,並顯示初始時間在網絡上頁面,但不會更新它三十秒(不確定,但這似乎是不變的,這可能有一些意義),然後,它開始每隔0.1秒更新一次時鐘。

  • 什麼是從websocket造成的錯誤信息?
  • 爲什麼它暫停三十秒後開始工作?
  • 這是一個合適的方法來結合AJAX和WebSocket?
  • 我該如何解決這些問題?

回答

0

問題原來是,瀏覽器正在請求一個favicon,我沒有設置。可能它等到超時,也許是三十秒,然後在那之後開始工作。該錯誤來自favicon請求。