Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrating WebSockets with Rails using Rack and Event Machine

I have created an Asynchronous version of Rails 3 that I would like to integrate with a WebSocket implementation.

I am using EventMachine, Ruby 1.9, Fibers and various em-flavoured libraries as documented by the wickedly good Ilya Grigorik.

I have been looking at em-websocket as the handler for WebSocket connections but unsure of the best approach for hooking this into a Rails app.

Ideally, this would work in a similar fashion to node.js with Express and Socket.io - incoming connections should be detected and dispatched to the WebSocket handler or the regular rails stack as indicated by the HTTP headers & etc.

TL;DR

  • WebSocket handler that plugs into an existing Rails application
  • Transparently dispatch incoming WebSocket requests to endpoints in the app
like image 696
Toby Hede Avatar asked Nov 22 '10 10:11

Toby Hede


2 Answers

I know this question is old but hopefully this answer may help those that have been directed here from google.

I am working on a gem that satisfies the two main criteria in the original question. The gem is called websocket-rails and has been developed from the ground up to make using WebSockets inside of a Rails application drop dead simple. It is finally at a stable release, but there is a whole lot more functionality that I believe it needs.

Currently, event handling is very basic. There is an events.rb file where you map client side events to controller actions similar to the routes.rb file. All requests to /websocket are passed through to the embedded WebSocket server without the need for a separate server process.

The more ambitious goal of the project is to eventually move Rails to a more traditional MVC pattern where events on the client browser bubble up to the server for processing and updating a model will automatically trigger events on the client to update the rendered representation of that model.

Any feedback would be appreciated.

like image 112
Dan Knox Avatar answered Oct 23 '22 08:10

Dan Knox


Check out Skinny.

You'll need to use Thin, but you can upgrade an HTTP request mid-stride. I use it in Sinatra apps, but it should be just as easily used in Rails.

like image 25
sj26 Avatar answered Oct 23 '22 09:10

sj26