You are viewing the legacy version of AdonisJS. Visit https://adonisjs.com for newer docs. This version will receive security patches until the end of 2021.

Philosophy

This guide covers the philosophy of the WebSocket server.

By the end of this guide, you will know about channels, topic subscriptions and multiplexing.

Pure WebSockets

AdonisJs uses pure WebSockets and doesn’t rely on polling.

Using pure WebSockets (supported by all major browsers), AdonisJs makes it easier to scale apps horizontally within a Node.js cluster without any 3rd party dependencies (e.g. Redis) and without the need for sticky sessions.

Multiplexing

Multiplexing reuses the same TCP connection while separating event and authentication layers between channels.

Multiplexing maintains a single connection from client to server, with AdonisJS providing a clean abstraction layer to manage channel subscriptions and exchange your application messages.

Channels & Topics

Once a client makes a WebSocket connection, they are required to subscribe to a topic in order to exchange messages.

Channels and topics are interrelated, so let’s write some code to better understand them.

Register a channel like so:

Ws.channel('chat', ({ socket }) => {
  console.log(socket.topic)
})

In the example above, all subscriptions to the chat channel have a static topic called chat (i.e. the channel and the topic name are same).

To register a channel with dynamic/wildcard topics:

Ws.channel('chat:*', ({ socket }) => {
  console.log(socket.topic)
})

In the example above, the chat channel accepts dynamic topics, so a user could subscribe to the channel chat:watercooler, chat:intro, chat:news, etc.

This dynamic/wildcard approach opens up an exciting world of creative possibilities (e.g. dynamic topics for private chats between two users).

Data Encoders

The WebSocket server uses data encoders when passing messages.

By default, the WebSocket server uses the JSON encoder, which has limitations when passing binary data.

If required, the AdonisJs @adonisjs/msgpack-encoder package can be used to handle ArrayBuffers and Blobs.

Message Packets

Multiplexing requires a standard to define data packet structure.

As a consumer of the WebSocket server package you don’t have to worry about packet types, but when writing a client for the server, it’s critically important to understand them.

Your WebSocket data encoder decodes network data as an object (or equivalent data type for your programming language) containing a structure similar to:

{
  t: 7,
  d: {
    topic: 'chat',
    data: 'hello world'
  }
}
  1. The property t is the type of the packet (we use numbers over strings, since numbers are less data to transfer).

  2. The property d is the data associated with that packet.

Learn more about AdonisJs WebSocket packets here.