0

I'm new in Ruby.

I'm trying to use WebSocket connection. So I use em-websocket gem. I also use Thin web server. I did everything like example told me to. So please help me out.

But server keep returning me:

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

Client request:

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

Client side code:

$(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'); };

    });

And here is server side code:

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
artie18
  • 3
  • 1

1 Answers1

0

EventMachine is listening on port 8000: EventMachine::WebSocket.start(:host => "0.0.0.0", :port => 8000) but you are trying to connect to port 3000: ws = new WebSocket("ws://localhost:3000/home/webSocket");

Change it to connect to port 8000:

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

Although the additional path is not needed unless you specifically want to pass /home/webSocket to EventMachine.

Tomdarkness
  • 3,800
  • 2
  • 21
  • 26