Skip to content

kacperk/sockjs-ruby

 
 

Repository files navigation

About

Disclaimer: This library is still work in progress.
(It is coming together though)

SockJS is WebSocket emulation library. It means that you use the WebSocket API,
only instead of WebSocket class you instantiate SockJS class. I highly
recommend to read SockJS: WebSocket
emulation

on the RabbitMQ blog for more info.

Prerequisites

Even though this library uses Rack interface, Thin is required as it
supports asynchronous
callback
.
For Websockets, we use
faye-websocket
gem.

The Client-Side Part

For the client-side part you have to use JS library
sockjs-client which provides
WebSocket-like API. Here’s an example:

<script src="http://cdn.sockjs.org/sockjs-0.2.1.min.js"></script>

<script>
  var sock = new SockJS("http://mydomain.com/my_prefix");

  sock.onopen = function() {
    console.log("open");
  };

  sock.onmessage = function(e) {
    console.log("message", e.data);
  };

  sock.onclose = function() {
    console.log("close");
  };
</script>

The Server-Side Part

Now in order to have someone to talk to, we need to run a server. That’s exactly what is sockjs-ruby good for:

#!/usr/bin/env ruby
# encoding: utf-8

require "rack"
require "rack/sockjs"
require "eventmachine"

# Your custom app.
class MyHelloWorld
  def call(env)
    body = "This is the app, not SockJS."
    headers = {
      "Content-Type" => "text/plain; charset=UTF-8",
      "Content-Length" => body.bytesize.to_s
    }

    [200, headers, [body]]
  end
end


app = Rack::Builder.new do
  # Run one SockJS app on /echo.
  use SockJS, "/echo" do |connection|
    connection.subscribe do |session, message|
      session.send(message)
    end
  end

  # ... and the other one on /close.
  use SockJS, "/close" do |connection|
    connection.session_open do |session|
      session.close(3000, "Go away!")
    end
  end

  # This app will run on other URLs than /echo and /close,
  # as these has already been assigned to SockJS.
  run MyHelloWorld.new
end


EM.run do
  thin = Rack::Handler.get("thin")
  thin.run(app.to_app, Port: 8081)
end

For more complex example check examples/sockjs_apps_for_sockjs_protocol_tests.rb

SockJS Family

Development

Get sockjs-protocol (installation information are in its README) and run rake protocol_test. Now you can run the tests against it, for instance:

# Run all the tests.
./venv/bin/python sockjs-protocol-0.2.1.py

# Run all the tests defined in XhrStreaming.
./venv/bin/python sockjs-protocol-0.2.1.py XhrStreaming

# Run only XhrStreaming.test_transport test.
./venv/bin/python sockjs-protocol-0.2.1.py XhrStreaming.test_transport

Links

Contributors

  • Judson Lester ( @nyarly )
  • Kacper Kawecki ( @kacperk )

About

WebSocket emulation - Ruby server

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Ruby 98.8%
  • Shell 1.2%