Using WebSockets in Rails: Real-Time Chat Application
WebSockets provide a powerful and efficient way to enable real-time communication between clients (browsers) and servers. In this article, we will explore how to use WebSockets in Ruby on Rails to build a real-time chat application.
WebSockets: What are they?
WebSockets are a communication protocol that allows for full-duplex communication channels over a single TCP connection. Unlike traditional HTTP requests that follow a request-response pattern, WebSockets provide a persistent connection, enabling real-time data exchange between the client and server.
Integrating WebSockets in Rails
Ruby on Rails provides the Action Cable
framework, which seamlessly integrates WebSockets into Rails applications. Action Cable allows us to leverage the power of WebSockets without worrying about low-level implementation details.
First, we need to uncomment the line gem 'actioncable'
in the Gemfile and run bundle install
to install the Action Cable gem.
// Gemfile
gem 'actioncable'
// Terminal
$ bundle install
Next, we need to generate a new channel using the following command:
// Terminal
$ rails generate channel Chat
This command creates a new file chat_channel.rb
inside the app/channels
directory. Open the chat_channel.rb
file and define the subscribed
and unsubscribed
methods:
// app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
def subscribed
stream_from 'chat_channel'
end def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
The subscribed
method specifies the channel to which the client subscribes. In this case, we are using the 'chat_channel'
. The stream_from
method creates a subscription to the specified channel.
Building the Chat Interface
Now that our WebSocket channel is set up, let’s build the chat interface in Rails. Create a new file chat.html.erb
and include the following HTML:
// app/views/chat/chat.html.erb
Real-Time Chat
The above HTML code sets up a chat interface with a container to display messages, an input field to type messages, and a send button. We include a JavaScript file chat.js
, which we will create next.
Handling WebSocket Events in JavaScript
Create a new file chat.js
and include the following code:
// app/assets/javascripts/chat.js
document.addEventListener('DOMContentLoaded', function() {
var messagesContainer = document.getElementById('messages');
var messageInput = document.getElementById('message_input');
var sendButton = document.getElementById('send_button');
App.chat = App.cable.subscriptions.create('ChatChannel', {
received: function(data) {
var messageElement = document.createElement('div');
messageElement.textContent = data.message;
messagesContainer.appendChild(messageElement);
}
}); sendButton.addEventListener('click', function() {
var message = messageInput.value;
App.chat.send({ message: message });
messageInput.value = '';
});
});
This JavaScript code handles the WebSocket events and updates the UI accordingly. The received
method is invoked whenever a new message is received from the server. It appends the message to the messagesContainer
. The sendButton
event listener sends the typed message through the WebSocket connection, and the input field is cleared.
Testing the Chat Application
Finally, start your Rails server and navigate to the chat page (http://localhost:3000/chat
for example). Open the chat page in different browsers or tabs and start sending messages. You should see the messages being displayed in real-time across all connected clients.
Congratulations! You have successfully built a real-time chat application using WebSockets in Ruby on Rails.
Conclusion
WebSockets offer a powerful way to build real-time applications. With the Action Cable framework in Ruby on Rails, integrating WebSockets becomes straightforward. By following the steps outlined in this article, you can create your own real-time chat application and explore further possibilities with WebSockets.
Leave a Reply