What is Socket.IO ?

What is Socket.IO ?

What is Socket.IO ?

socket.io

I recently built an basic real-time chat application and I used socket.io for the implementation of bi-directional communication between a client and a server.

What’s Socket.IO exactly?

Socket.IO is a JavaScript library for real-time web applications. It allows bi-directional communication between client and server. Bi-directional communications are enabled when a client has Socket.IO in the browser, and a server has also integrated the Socket.IO package. Socket.IO are needed when we need real-time in our app.

Let me explain this in little more detail. Let’s assume you want to build a two-way communication(Chat app) functionality. It can be done by using Socket.IO. With sockets, when the server receives a new message it will send it to the client and notify them, bypassing the need to send requests between client and server.

How to implement Socket.IO in chat app ? Prerequisites: node

Server

  • Create a new folder:
$ mkdir socket.io-chatapp
$ cd socket.io-chatapp
$ npm install express socket.io
  • Create a file named server.js & setup server & required packages:
const app = require("express")();
const http = require("http").createServer(app);
const io = require("socket.io")(http);
  • The server root will send our index.html

app.get("/", (req, res) => res.sendFile(__dirname + "/index.html"));

  • Setup Socket.IO It is listening for a ‘connection’ event and will run the provided function anytime this happens.
io.on("connection", function(socket) {
 console.log(“Socket Connected!”);
});
  • Setup Port http.listen(3000, () => console.log("Listening on localhost:3000"));
  • Run the application node server.js

Client

  • Create a main.js file & Your socket connection is setup! // establish socket.io connection const socket = io();

Server

  • Inside the function we are using io.emit() to send a message to all the connected clients. This code will notify when a user connects to the server.
io.on("connection", function(socket) {
 io.emit(“User joined”);
});
  • We will also add a listener for any new messages received from a client and send a message to all users in response.
io.on("connection", function(socket) {
 io.emit(“User joined”);
 socket.on(“message", function(msg) {
   io.emit("message", msg);
 });
});

Client

  • Create an index.html file for the chat form, copy the following code below.
<!DOCTYPE html>
<html lang="en">
 <head>
   <meta charset="UTF-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <meta http-equiv="X-UA-Compatible" content="ie=edge" />
   <title>Socket.io Example App</title>
 </head>

 <body>
   <h1>Socket.io Chat Application</h1>
   <div>
     <h2>Messages</h2>
     <ul></ul>
   </div>
   <form action="">
     <input type="text" />
     <button>Send</button>
   </form>
   <script src="/socket.io/socket.io.js"></script>
 </body>
</html>
  • Now let’s add logic in our main.js file
// select relevant elements
 const form = document.querySelector("form");
 const input = document.querySelector("input");
 messageList = document.querySelector("ul");

 // establish socket.io connection
 const socket = io();

 // handle sending message to server & input reset
 function sendMessage(e) {
   // prevent form submission refreshing page
   e.preventDefault();
   // send input value to server as type 'message'
   socket.emit("message", input.value);
   // reset input value
   input.value = "";
 }

 // add listener to form submission
 form.addEventListener("submit", sendMessage);

 // add message to our page
 function addMessageToHTML(message) {
   // create a new li element
   const li = document.createElement("li");
   // add message to the elements text
   li.innerText = message;
   // add to list of messages
   messageList.append(li);
 }
  // watch for socket to emit a 'message'
 socket.on("message", addMessageToHTML);

 // display message when a user connects
 function alertUserConnected() {
   addMessageToHTML("User joined");
 }
  // watch for socket to emit a 'user connected' event
 socket.on("user connected", alertUserConnected);

After completing these steps your socket.io application should be up and running!

Thanks for reading