How would you implement WebSockets in a Rails application without using Action Cable?

When building real-time features in a Rails application, Action Cable is often the go-to solution. However, there might be scenarios where you need alternative approaches to implement WebSockets without using Action Cable. This could be due to specific project requirements, a different server setup, or just wanting to explore other technologies.

Why Avoid Action Cable?

While Action Cable is a powerful integration for handling WebSockets in Rails, it might not always fit every use case. It tightly couples with Rails and might not be as flexible when dealing with a non-standard infrastructure or when integrating with other non-Rails components. This article explores alternative strategies for implementing WebSockets in a Rails application without using Action Cable.

Alternative WebSocket Libraries

Several Ruby libraries and external services can assist in implementing WebSockets. Let's explore a couple of popular options:

1. Faye

Faye is a simple and robust publish-subscribe messaging system that can be integrated with Rack applications. It's a flexible alternative for WebSockets and can work seamlessly with Rails.

Example Setup:

First, add Faye to your Gemfile:

ruby
1gem 'faye-websocket'
2gem 'eventmachine'
3

Then, create a Faye server:

ruby
1# faye_server.ru
2require 'faye/websocket'
3require 'rack'
4
5App = lambda do |env|
6 if Faye::WebSocket.websocket?(env)
7 ws = Faye::WebSocket.new(env)
8
9 ws.on :message do |event|
10 ws.send('Echo: ' + event.data)
11 end
12
13 ws.on :close do |event|
14 ws = nil
15 end
16
17 ws.rack_response
18 else
19 [200, {'Content-Type' => 'text/plain'}, ['Hello']]
20 end
21end
22
23run App
24

To run your Faye server, use Rack:

shell
1rackup faye_server.ru -s thin -E production
2

2. AnyCable

AnyCable allows you to replace Action Cable with a Go-based WebSocket server, boosting performance. It's particularly useful when dealing with high concurrency WebSocket connections.

Start by installing AnyCable:

ruby
1gem 'anycable-rails'
2

Configure your Rails environment and server accordingly. AnyCable requires a separate server running, but it seamlessly integrates with Rails.

Implementing WebSockets Without a Library

If your needs are minimal, you can also implement a basic WebSocket server using other technologies, like Node.js, that can interface with Rails. Here's a simple example with Node.js and the popular ws library:

Node.js Setup:

Create a simple WebSocket server in Node.js:

javascript
1// server.js
2const WebSocket = require('ws');
3
4const wss = new WebSocket.Server({ port: 8080 });
5
6wss.on('connection', (ws) => {
7 ws.on('message', (message) => {
8 console.log('received: %s', message);
9 ws.send(`Echo: ${message}`);
10 });
11
12 ws.send('Welcome to WebSocket server');
13});
14

To start your Node.js WebSocket server, use:

shell
1node server.js
2

WebSocket Client Integration

Once your WebSocket server is ready, you can connect from a Rails frontend using JavaScript:

javascript
1document.addEventListener("DOMContentLoaded", function() {
2 const socket = new WebSocket('ws://localhost:8080');
3
4 socket.onopen = function() {
5 console.log('WebSocket connection established');
6 socket.send('Hello, Server!');
7 };
8
9 socket.onmessage = function(event) {
10 console.log('Message from server ', event.data);
11 };
12});
13

Conclusion

Choosing an alternative WebSocket solution can offer flexibility and meet specific project demands better than Action Cable in certain situations. Whether you decide to use Faye, AnyCable, or roll out a custom solution with Node.js, Rails can accommodate your real-time web application needs effectively. Explore these options and decide which fits your project best.

For more insights on WebSockets and real-time web applications, you might find these resources helpful:

Embrace the power of WebSockets and enhance your application's interactivity without being tied to Action Cable!

Suggested Articles