2013-02-15 82 views
0

我是Ruby中的新成員。使用em-websocket gem無法更改連接到'ws://'RUBY

我正在嘗試使用WebSocket連接。所以我使用em-websocket寶石。 我也使用瘦Web服務器。我做了所有例子都告訴我。所以請幫助我。

但服務器的回頭率我:

HTTP/1.1 200 OK 
Content-Type: text/html; charset=utf-8 
X-UA-Compatible: IE=Edge 
ETag: "7592ed842deb971babc6640ff75207fb" 
Cache-Control: max-age=0, private, must-revalidate 
X-Request-Id: f2d12b00aa2eb202b24c309ce0570da0 
X-Runtime: 0.008190 
Connection: close 
Server: thin 1.5.0 codename Knife 

客戶端請求:

GET /home/webSocket HTTP/1.1 
Upgrade: websocket 
Connection: Upgrade 
Host: localhost:3000 
Origin: http://localhost:3000 
Pragma: no-cache 
Cache-Control: no-cache 
Sec-WebSocket-Key: i6Efmjpxmz2GOFpjduxoyA== 
Sec-WebSocket-Version: 13 
Sec-WebSocket-Extensions: x-webkit-deflate-frame 

客戶端代碼:

$(document).ready(
    function() { 
     ws = new WebSocket("ws://localhost:3000/home/webSocket"); 
     ws.onopen = function() { 
      alert('open'); 
      ws.send("hello server"); 
     }; 
     ws.onmessage = function(evt) { alert(evt.data); }; 
     ws.onclose = function() { alert('close'); }; 

    }); 

這裏是服務器端代碼:

def webSocket 
    require "rubygems" 
    require "em-websocket" 

    EventMachine.run { 
    EventMachine::WebSocket.start(:host => "0.0.0.0", :port => 8000) do |ws| 
    ws.onopen { |handshake| 
     puts "WebSocket opened #{{ 
      :path => handshake.path, 
      :query => handshake.query, 
      :origin => handshake.origin, 
     }}" 

     ws.send "Hello Client!" 
     } 
     ws.onmessage { |msg| 
     ws.send "Pong: #{msg}" 
     } 
     ws.onclose { 
     puts "WebSocket closed" 
     } 
     ws.onerror { |e| 
     puts "Error: #{e.message}" 
     } 
     end 
    } 
    end 

回答

0

EventMachine的正在偵聽端口8000: EventMachine::WebSocket.start(:host => "0.0.0.0", :port => 8000)但您嘗試連接到端口3000:ws = new WebSocket("ws://localhost:3000/home/webSocket");

更改它連接到端口8000:

ws = new WebSocket("ws://localhost:8000/home/webSocket");

雖然額外的路徑不需要,除非您特別想將/home/webSocket傳遞給EventMachine。

+0

非常感謝。它現在工作完美。 – artie18 2013-02-15 21:13:07