Creating the Chat Server Functionality

With your WebSockets server up and running, you are now ready to build out your chat server. Your chat server needs to do a few things:

  • keep a log of the messages sent so far to the server

  • broadcast older messages to new people joining the chat

  • broadcast new messages to all clients

Keeping a log of messages as your users send them is necessary in order to send the message history to new users, so you will tackle that first.

In websockets-server.js, create an array to hold on to messages.

var WebSocket = require('ws');
var WebSocketServer = WebSocket.Server;
var port = 3001;
var ws = new WebSocketServer({
    port: port
});
var messages = []; console.log('websockets server started'); ... ...

Get Front-End Web Development: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.