Websockets 101

Building a chatroom with Node's ws module

Repo: https://github.com/mohammedabdulwahhab/socket-chatarrow-up-right

HTTP wasn't really designed for many of the applications now served over the web - namely those requiring a lot of real-time, low-latency input from the server (i.e chat apps, games, etc.). This is primarily because any browser-server exchange over HTTP requires initiation from the browser.

In addition, the stateless design of HTTP meant that frequent polling to simulate server initiated events would be costly due to the added overhead demanded by HTTP. Cue websockets - a way to initiate bi-directional communication sessions between the browser and the server.

In the section below, we setup a simple anonymous chat room (didn't feel like going the whole 9 yards to add users). I believe the example highlights most of Websocket's coolest features (i.e a chat room in around 30 lines of server side code)

Server.js

server.js
const express = require('express')
const app = express()
const WebSocket = require('ws').Server
// Set middleware on the app
// Serve statics including index.html
app.use(express.static('public'))

// Start the server listening on 2000 and get the server
const httpServer = app.listen(2000)

// Create a new web socket server from our existing http server
const wsServer = new WebSocket({
    server: httpServer
})

wsServer.on('connection', (wsClient, req) => {
    console.log('New client just connected!')
    forwardMessagetoClients('New member in chat')
    // Broadcast message that client send to all clients
    wsClient.on('message', forwardMessagetoClients)
    wsClient.on('close', () => {forwardMessagetoClients('A client left the chat')})
})

function forwardMessagetoClients(message){
    // Forward message to all clients inclduing sender - wsServer keeps a list of active clients
    wsServer.clients.forEach((client) => {
        client.send(message)
    });
}

A couple notes:

Client.js

Running your app should get you to a view like this:

index.html

Socket.io

My understanding is that Socket.io is supposed to implement a number of abstractions on top of these modules to aid in in development of larger WebSocket based applications.

Last updated