In this chapter, you will learn how to use the Action Cable feature in Rails to build a real-time chat application that employs the WebSocket protocol.
What are WebSockets?
The World Wide Web primarily works on the principle of REST, which encapsulates the HTTP protocol. However, one of its drawbacks is that it can be slower for real-time updates since it initiates a fresh connection each time.
WebSockets are highly efficient for real-time data exchange, providing low-latency communication. Unlike HTTP which provides a half-duplex communication, the WebSocket protocol enables full-duplex interaction between a web browser or any other client, and a web server with low overhead.
Most browsers including Chrome, Firefox and Edge, support the WebSocket protocol. The WebSocket protocol introduces ws (WebSocket) and wss (WebSocket Secure) as two new uniform resource identifier (URI) schemes.
The process of initiating the WebSocket communication starts with a client opening a HTTP connection with the server. The connection request has an upgrade header that specifies the WebSocket protocol. The server responds by including the upgrade header, indicating that it is switching to WebSocket protocol. This process is called as handshake.
A Real-time Chat App using WebSocket
Let us create a Rails application and enable Action Cable feature in it, to build a simple chat application that implements the WebSocket protocol.
To start with, create a new application –
rails new chat_app
cd chat_app
If you are using Rails version earlier than 8.0, then you will need to include action_cable gem in your GemFile â
gem "action_cable"
And then,
bundle install
You need not perform the above step, if you have the following in your Gemfile,
gem "rails","~> 8.0.0"
As Rails will automatically include the correct version of Action Cable.
You should mount the Action Cable in the application’s routing configuration by modifying config/routes.rb as:
Rails.application.routes.draw do
root "chatroom#index"
mount ActionCable.server =>"/cable"end
Your chat application provides a channel for the users. Use the generate command to generate Chatroom channel.
rails generate channel Chatroom
The messages entered by the users are characterized by the content attribute of the message model.
rails generate model Message content:text
rails db:migrate
You now have a Message table in the SQLite database, and the files app/channels/chatroom_channel.rb as well as a JavaScript code in app/javascript/channels/chatroom_channel.js
Update chatroom_channel.rb and define subscribed as well as receive methods in the ChatroomChannel class −
The subscribed Method is called automatically when the client sends a WebSocket message. It tells the server: "Start streaming messages from the chatroom broadcast to this client", while stream_from sets up a listener (stream) on the server side for the "chatroom" broadcast.
The receive method is called when the client sends a WebSocket message. It gets that data payload (after parsing JSON). It saves the message to the database and immediately re-broadcasts it back to all clients subscribed to "chatroom".
To create a Controller with an index action –
rails generate controller Chatroom index
Modify the index action to retrieve all the messages from the Message model â
How does this view function? Note that Rails mounts the WebSocket server as it starts. The index view starts a WebSocket client and sends a connection request. When the send Button in the browser is clicked, the text in the input box is received by the server and is stored in the Message model. The text area element of the web page is populated by the messages available so far.
With all the above steps accurately performed, run the Rails server. Open two tabs of your browser and try sending messages as shown in the figure below:
Leave a Reply