DEV Community

tjray-dev
tjray-dev

Posted on

'/Socket', to: 'me#'

A brief introduction to Websocket

There are many things to wonder about when you are just beginning to learn about programming. Some of them are big important questions like, "Am I more interested in front or back end development?" or "What languages should I learn?" Others are perhaps less important like, "What color palette should I use for my text editor?" and "How should I indent my code; four white-spaces, two white-spaces, maybe a good ol' fashioned tab?" (you get the point)

Today I'd like to explore a question that I recently found myself asking; "How do you send data between the client and server in real time?" Or to put it another way, "How does streaming work?"

Introducing Websocket! (cue dramatic intro...)

Wikipedia describes Websocket as

A computer communications protocol providing full-duplex communication channels over a single TCP connection...
Enter fullscreen mode Exit fullscreen mode

which is fancy tech talk for "it creates a two lane road between the client and server". Websocket operates similarly to the HTTP request -> response cycle but is still distinct from it in that it allows the server to send data to the client with out a specific request for said data. Put more tersely, Websocket allows data streaming.

Websocket is a relatively new technology as it was first standardized in 2011 by the IETF (internet engineering task force)

It is also supported by most web browsers.

But how might one go about implementing this technology into their web apps? Well if you are building a rails app then you are in luck. Let's now introduce Action Cable (Yay! Action Cable! So Cool!)

Action Cable

Action cable is built into rails and is similar is concept to Controllers in the MVC model. It provides both a server side and client side framework, in ruby and JavaScript respectively. This allows seamless integration of Websocket into your rails apps. Now about that structure I mentioned.

On the server side you have a few key components:

The connection -> a connection instance is created whenever a user starts a new websocket with the server, its concerns are the authentication and authorization of a connection and handling of exceptions. The connection object becomes the parent class of all Channels created under it. (similar to how controllers inherit from the application controller)

The Channel -> Channels encapsulate the work of handling subscriptions. In other words the Channel defines all of the actions that can be made to a subscription by a connection. (Just like you would have a separate controller to handle the actions that a user can take on an instance of a model)

The Subscription -> Subscriptions are an instance of a channel allowing for the flow of data between a client and server

PUB/SUB -> (Pub)lishers send data to a class of unspecified recipients, the (Sub)scribers.

Broadcastings -> A Broadcasting is the link between a client and the server as defined by the subscriptions unique to the user. A channel can have multiple broadcastings.

Here is an example of a basic connection class

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
    end

    private
      def find_verified_user
        if verified_user = User.find_by(id: cookies.encrypted[:user_id])
          verified_user
        else
          reject_unauthorized_connection
        end
      end
  end
end
Enter fullscreen mode Exit fullscreen mode

and the channel parent class

module ApplicationCable
  class Channel < ActionCable::Channel::Base
  end
end
Enter fullscreen mode Exit fullscreen mode

a child channel with actions

class AppearanceChannel < ApplicationCable::Channel
  def subscribed
    current_user.appear
  end

  def unsubscribed
    current_user.disappear
  end

  def appear(data)
    current_user.appear(on: data['appearing_on'])
  end

  def away
    current_user.away
  end
end
Enter fullscreen mode Exit fullscreen mode

from here method calls of Create and broadcast are used between the client and server to send data back and forth.

While this is only a surface level overview of Action cable and its capabilities I hope it is enough to intrigue some and encourage further exploration of this useful technology to build ever more interesting apps.

Top comments (0)