Getting Started with Socket.io

Socket.io is a Javascript library for web apps that allows real-time communication between clients and servers.It has two parts: a client-side library that runs in the browser, and a server-side library for node.js. Both components have a nearly identical API. Like node.js, it is event-driven.Chat apps or social media feeds in which a user's page (client) receives messages or posts from other users are the most frequent use cases for Websockets and socket.io.

Socket.IO primarily uses the websocket protocol with polling as a fallback option,while providing the same interface. Although it can be used as simply a wrapper for webSocket, it provides many more features, including broadcasting to multiple sockets, storing data associated with each client, and asynchronous I/O.

In this article,we’ll create a basic chat application that allows users to talk to each other in real-time.Our application will consist of two separate components, a server, and a client, each one with different responsibilities:

Server responsibilities for our chat app

  • Serve the HTML, CSS and JavaScript client files to the users
  • Start the Socket.io connection
  • Receive events from clients (like a new chat message) and broadcast them to other clients

Client responsibilities for our chat app

  • Load socket.io client library
  • Establish connection with the Socket.io running in our server
  • Emit and receive events to/from Socket.io running in our server
  • Add our own messages to the chat via JavaScript

Now that we know what do we need to build, let's get started!

Check NodeJs installed

Checking whether nodejs is installed on your pc by printing its version using the following command in Command Prompt:

1. > node -v
v14.16.0

If you are not getting any version printed out on your terminal,it means that you don't have NodeJs installed on your pc.Download the installer from NodeJS WebSite..

Creating A Folder For Our Chat Application

Now, let's create a new folder for our project:

mkdir chat-app
cd chat-app

mkdir makes a new directory.
cd changes the current working directory.

Now that we are in the correct directory.We can start by initializing npm to get our new project setup.

Initialize npm

Once you have navigated to the correct folder, you can initialize npm on that folder:

npm init -y

With node,technically,we could code our own basic web server from scratch.However, in the real world people don't do that.In the real world,there's a super famous package called express.Express is the industry standard for creating Servers in node.

Installation of Express

The above statement means that install express at the specify version number.

In the chat-app folder,create a new file called index.js.

Configure our server

Inside index.js add the following code:

1. const express=require('express');
2. const app=express();

3. app.get('/',(req,res)=>{
   res.send('Express is up and running!');
})

4. const port=process.env.PORT || 3000;

5. app.listen(port,()=>{
  console.log(`Server is listening on port ${port}`);
});

Explanation of the above code:

Line 1:The require function is used to import the library express which is being stored in a variable called express.The express library exposes just a single function.So,express is actually a function as opposed to something like an object.We call it to create a new express application.

Line 2:Is used to configure our server by using various methods provided on the application itself.

Line 4:Is the port you want the app to listen on.

Line 5:Is used to start the server and makes it listen on a specific port.

You can start the server by calling node with the script in your command prompt:

node index.js
Server is listening on port 3000

In the chat-app folder,create a sub-directory called public.
Inside the public folder,create a new file called index.html.
Inside index.html add the following code inside:

<!DOCTYPE html>
<html>
<head>
<title>Socket.IO chat</title>
</head>
<body>
<h1>Socket.io Chat App</h1>

</body>
</html>

Inside index.js replace

1. const express=require('express');
2. const app=express();

3. app.get('/',(req,res)=>{
   res.send('Express is up and running!');
})

4. const port=process.env.PORT || 3000;

5. app.listen(port,()=>{
  console.log(`Server is listening on port ${port}`);
});

with this:

1. const path=require('path');
2. const express=require('express');

3. const app=express();


4. const port=process.env.PORT || 3000;
5. const publicDirectoryPath=path.join(__dirname,'/public');

6. app.use(express.static(publicDirectoryPath));

7. app.listen(port,()=>{
  console.log(`Server is listening on port ${port}`);
});

Now,that we are done with the changes.we can start the server by calling node with the script in your command prompt:

node index.js
Server is listening on port 3000

Getting Started with Socket.io

1.0 Install socket.io

Socket.io is not a native package to Node, so it must be installed. Because you want to ensure it's included in your node modules, make sure to install it locally and then require it in your server.

Now install socket.io in the chat-app directory by running the command npm install [email protected] in command prompt:

npm install [email protected]

The dependencies section of your package.json will now appear at the end of the package.json file and will include socket.io.

{
  "name": "chat-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.4",
    "socket.io": "^2.2.0"
  }
}

Basic Setup with Express:

Express app can be passed to http server which will be attached to socket.io .
Now let’s edit index.js to add it:

const path=require("path");
const http=require("http");
const express=require('express');
const socketio=require('socket.io');



const app=express();
const server=http.createServer(app);
const io=socketio(server);


const port=process.env.PORT || 3000;
const publicDirectoryPath=path.join(__dirname,"/public");

app.use(express.static(publicDirectoryPath));


io.on("connection",(client)=>{
    console.log('New websocket connection');

})

server.listen(port,()=>{
    console.log(`Server is up on port ${port}!`);
})

Notice that I initialize a new instance of socket.io by passing the server (the HTTP server) object. Then I listen on the connection event for incoming sockets and log it to the console.

Now in index.html add the following snippet before the </body>(end body tag):

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io();
</script>

That’s all it takes to load the socket.io-client, which exposes an io global, and then connect.

Running node index.js again,if it's already running restart the process by pressing control + c and then run node index.js again.Now,point your browser to http://localhost:3000. You should see the console print something out 'New websocket connection'

Each socket also fires a special disconnect event:

io.on('connection', (client) => {
  console.log('New websocket connection');
  client.on('disconnect', () => {
    console.log(''New websocket disconnected');
  });
});

The most used functions when working with Socket.io are socket.emit(eventName, data) and socket.on(eventName, data) to emit and capture events in both the server and the clients.The socket.emit() is used to send data and socket.on() is used to receive data.As a rule of thumb, just remember to have an socket.on() function for each event you send with socket.emit().

NB:The eventName can be any custom name you want to call it.

Example:Basic Chat App

In index.js edit the file:

const path=require("path");
const http=require("http");
const express=require('express');
const socketio=require('socket.io');



const app=express();
const server=http.createServer(app);
const io=socketio(server);


const port=process.env.PORT || 3000;
const publicDirectoryPath=path.join(__dirname,"/public");

app.use(express.static(publicDirectoryPath));


io.on("connection",(client)=>{
    console.log('New websocket connection');
 client.on('messageFromClient', msg => {
    io.emit('messageFromServer', msg);
  });
   client.on('disconnect', () => {
    console.log('New websocket disconnected');
  });
})

server.listen(port,()=>{
    console.log(`Server is up on port ${port}!`);
})

Inside index.html edit the file:

<!DOCTYPE html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      body { margin: 0; padding-bottom: 3rem; font-family: Helvetica, Arial, sans-serif; }

      #form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
      #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
      #input:focus { outline: none; }
      #form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }

      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages > li { padding: 0.5rem 1rem; }
      #messages > li:nth-child(odd) { background: #efefef; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form id="form" action="">
      <input id="input" placeholder="Say Something..." autocomplete="off" /><button>Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>

    <script>
      var socket = io();

      var messages = document.getElementById('messages');
      var form = document.getElementById('form');
      var input = document.getElementById('input');

      form.addEventListener('submit', function(e) {
        e.preventDefault();
        if (input.value != "") {
          socket.emit('messageFromClient', input.value);
          input.value = '';
        }
      });

      socket.on('messageFromServer', function(msg) {
        var item = document.createElement('li');
        item.textContent = msg;
        messages.appendChild(item);
        window.scrollTo(0, document.body.scrollHeight);
      });
    </script>
  </body>
</html>

In the above code,two things happened.

//server (emit) -> client (receive) -messageFromServer
//client (emit) -> server(receive) -messageFromClient

If you've reached this point, thank you very much. I hope that this tutorial has been helpful for you and I'll see you all in the next.

If you like my work, please consider
Buy me a coffee
so that I can bring more projects, more articles for you

If you want to learn more about Web Development don't forget to follow me on Youtube!

19