What are Web Sockets?
Not that kind… but first…
Think about how most interactions with a website work. You arrive at the homepage and then navigate through various parts of the website by clicking links and the browser refreshes and renders new pages many times. Sometimes, however, this isn’t the most desired user experience. Think about a chat feature, for instance. It wouldn’t be very desirable for the user to have to refresh the page to send and receive each message. That’s where Web Sockets come in. Web Sockets allow for users to send and receive data in real time. They do this by maintaining an open flow of data between the client and the server.
In the typical HTTP request-response cycle, data is only sent and received on page reload. The client sends a request to the server, which sends some information back to the client. Then, the connection is terminated.
With a Web Socket implemented, after the connection is established between the client and server, it remains open and bi-directional. It allows for multiple users to be connected simultaneously and share the same information with each other.
Sounds great, right? Well, how do we implement this in our programs?
It depends on which language you work with and what framework you are using, but for our purposes today, we will be looking at how it is implemented in Ruby on Rails.
The foundation of the client-server is a Connection object that is created for each Web Socket initiated with the server. Connections become the parent class for each Channel class. The Channel objects function similarly to a controller in a typical MVC application. They break down logical pieces of work associated with each feature of a Web Socket. For example, if you were building a chat feature you would build a ChatChannel that inherits from ActionCable::Channel. Rails automatically creates a Channel (inheriting from ActionCable::Channel::Base) class that acts as a parent to all other channels and is available to store shared logic.
With a Connection class, some Channel classes, some ruby gems, and a little more set up, you can be ready to launch an application with real -time functionality.
For an example of a Web Socket in action, check out this simple implementation:
Web Sockets create a different request-response cycle to allow a continuous flow of information from client to server and back. In Rails, we can use ActionCable, which helps to integrate Web Sockets into typically structured Rails applications.
Check out this great tutorial on how to implement a chat feature with Action Cable! It gives an accessible introduction to the concept of Web Sockets, too!
The Rails documentation has a lot of good resources for establishing connections with your Web Sockets!