DEV Community

Cover image for Socket.io: Change Once, Update Everywhere
kymiddleton
kymiddleton

Posted on • Edited on

Socket.io: Change Once, Update Everywhere

In today’s busy world instant messaging applications for chatting with friends or colleagues are time savers and fun to use. Applications that allow collaboration such as Google docs that save data changes almost instantly are genius compared to the days of emailing document revisions back and forth. When multiple users are using the same application and content is displayed the same way, with additions or changes reflected immediately, it’s considered real-time.

Making a real-time web application isn’t all that difficult when the JavaScript library, Socket.IO, is used. The Socket.IO library enables real-time communication events with the events taking place between the server and the browser. There is a server-side library for Node.js as well as a client-side library that runs in the browser and the APIs for both are practically identical.

Socket IO is built on top of WebSockets which is an Internet protocol that allows communication between the server and clients then it goes beyond a typical route request response. With WebSockets, the server can send a route request response without the client initiating a request. Sockets provide a two-way communication channel between the client and server. The server can push messages to the clients and when events occur the server gets it and pushes it to the connected client. Socket.IO can broadcast to multiple sockets, store data associated with multiple clients or be used as a wrapper for WebSockets. It’s important to remember some older browsers do not support WebSockets however Socket.IO provides fallback mechanisms for this situation which is a nice feature.

Building a full stack application as a beginner requires a basic understanding of a few items: JavaScript, HTML, Node Package Manager (npm), Node.js and Express.js (Node HTTP or Node-server-side framework can also be used). To get started install Express and Socket.IO with the following command:

npm init

Once the prompted questions have been answered run:

npm install --save express socket.io

Next, implement the installed packages in a JavaScript file such as server.js to outline the require statements for Express and Socket.IO.

// Initialize Express
const app = express();

// Dependencies
const express = require(express);
const server = require(http).createServer(app);
const io = require(socket.io)(server);

// Set the port for the server to listen on

// Use body-parser for handling form submissions

// Set up Express to handle data parsing
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// Set the server to use the public directory for static assets
app.use(express.static(path.join(__dirname, 'public')));

// Socket.io Routes
require('./sockets/’<name of socket routes file> ')(io);

// Connect to database

// Start server on predefined PORT
server.listen(PORT, function(){
    console.log(`App is now listening on PORT ${PORT}`)
})

The program needs to know what steps to take when a connection is established and this can be created in a sockets.js file.

module.exports = function (io) {

    io.on('connection', function (socket) {

        //Socket Routes
            socket.on('new-todo', function(data){
            console.log(data);

            io.emit('emit-todo', data);
        socket.emit('emit-todo', data);
        })

        console.log('connected');
    })
}

When a new connection is established for new-todo the data will show in the console. It’s also important to note the different between io.emit() and socket.emit(). The io version io.emit() emits to everyone connected to the server and the socket version socket.emit() emits back to the initiating client.

Obviously, this only outlines the beginning framework of a Socket.IO application however once the initial nuances of building a full stack application are understood, Socket.IO can take a web application to the next level.

To learn more, check out the following resources:
Socket.IO Docs
Socket.IO Tutorial
ExpressJS Tutorial

Top comments (0)