h1. About
Disclaimer: This library is still work in progress.
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":http://www.rabbitmq.com/blog/2011/09/13/sockjs-websocket-emulation on the RabbitMQ blog for more info.
h2. Prerequisites
Even though this library uses Rack interface, Thin is required as "it supports asynchronous callback":http://macournoyer.com/blog/2009/06/04/pusher-and-async-with-thin. For Websockets, we use "faye-websocket":http://blog.jcoglan.com/2011/11/28/announcing-faye-websocket-a-standards-compliant-websocket-library gem.
h2. The Client-Side Part
For the client-side part you have to use JS library "sockjs-client":http://sockjs.github.com/sockjs-client which provides WebSocket-like API. Here's an example:
h2. 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":https://github.com/sockjs/sockjs-ruby/blob/master/examples/sockjs_apps_for_sockjs_protocol_tests.rb
h2. SockJS Family
h1. Development
Get "sockjs-protocol":https://github.com/sockjs/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
h1. Links