Basics you need to know to get started with Socket.io!
socket.io, web-sockets, related terminologies and everything! 🔥
Table of contents
SOCKET.IO?
Lets get going from the very basic, very start and define socket.io.
It is basically a library that enables,
low-latency: latency means delay, hence low/negligible delay in the communication where data is frequently updating or changing.
bidirectional: communication happens in both direction between 2 or more parties.
event-based communication: everything is controlled and based on events,
between a client and a server.
It is built on top of the WebSocket protocol and provides additional guarantees like a fallback to HTTP long-polling or automatic reconnection.
WebSocket is a communication protocol which provides a full-duplex and low-latency channel between the server and the browser.
HOW DOES IT ACTUALLY WORK?
All it is doing here is simply connecting client to the server, but making the connection stay or persist. Lets review the concept through a diagram.
Lets say we want to make several fetch requests or ajax requests to the server, each one will require a new request hit, as shown below.
- So, we use WebSocket to connect with the server. If we make any number of requests through our WebSocket, still it will need to connect only once, since here connection will stay open.
- This is really useful when we need to make multiple smaller requests to the server, since we can constantly communicate with the server, without setting up the connection and tearing down again once the request ends.
- Setting up connections and tearing them down can be proven very time-consuming when multiple requests/communication to the server is made, which is where WebSockets come into play!
DEVELOPMENT
There are 2 ends in the development using socket.io, Client and Server.
SERVER API
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.
FORMAT
io.on("connection", function(socket) {
io.emit(“user connected”);
});
If you want to broadcast to everyone except the person who connected you can use socket.broadcast.emit().
CLIENT API
<script type="module">
import { io } from "https://cdn.socket.io/4.4.1/socket.io.esm.min.js";
const socket = io();
</script>
Lets build a small demo using these concepts:
Dependencies required:
- express
- socket.io
- ejs
- nodemon
We use command in terminal:
npm i express socket.io ejs nodemon
Your File structure should look like,
home.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Socket.io</title>
<script src="https://cdn.socket.io/4.5.3/socket.io.min.js" integrity="sha384-WPFUvHkB1aHA5TDSZi6xtDgkF0wXJcIIxXhC6h8OT8EH3fC5PWro5pWJ1THjcfEi" crossorigin="anonymous"></script>
</head>
<body>
<input type="text" class="message">
<button onclick="sendMessage()" >Send Message</button>
<h1></h1>
<script>
const socket = io('http://localhost:3000');
//event
socket.on('connection');
socket.on('message', (data)=> {
document.querySelector('h1').innerHTML = data;
})
const sendMessage = () => {
const messageInput = document.querySelector('.message');
const message = messageInput.value;
console.log("this is a message i clicked" + message)
socket.emit('message', message);
}
</script>
</body>
</html>
index.js --> SERVER
const express = require("express");
const app = express();
const server = require('http').createServer(app);
const io = require("socket.io")(server, {cors: {origin: "*"}});
app.set('view engine', 'ejs');
app.get("/home", (req,res)=> {
res.render('home')
});
server.listen(3000, ()=> {
console.log("Server running...");
})
//event emmitter
//each socket is a connection with diff id.
io.on('connection', (socket)=> {
console.log("user connected: " + socket.id);
//event for receiving
socket.on("message", (data) => {
// console.log(data);
socket.broadcast.emit("message", data)
})
})
Now, to run the server :
nodemon index.js
We get to see the output as follows:
Now whenever a request is hit on the URL, a new user with unique id is generated(user enters the room.). If we log the ids we can conclude that each user is identified using unique id.
FUTURE?
We can observe the stats clearly, popularity of socket.io is quite cohesive,while other libraries are growing more rapidly!