DEV Community

Cover image for Introduction to Web Socket
Gyanshu Kumar
Gyanshu Kumar

Posted on

Introduction to Web Socket

Socket.IO is a JavaScript library that enables real-time, bidirectional communication between web clients (like browsers) and servers. It’s particularly useful for building interactive web applications where data needs to be transmitted instantly and continuously between the client and the server.

It's popular for applications like chat, gaming, and live data updates. It works across platforms, handles fallbacks gracefully, offers event-driven architecture, supports rooms and namespaces, scales well, and has a strong community for support.
How Work
Connection Establishment: When a client wants to establish a real-time connection with the server, it initiates a WebSocket handshake. If WebSocket support is available, Socket.IO uses it for communication. If not, it falls back to other transport mechanisms like long polling.

Event-Based Communication: Once the connection is established, both the client and the server can emit events and listen for events. Events are essentially messages that can carry data and trigger actions on the other side.

Bi-Directional Communication: Socket.IO allows both the client and the server to send and receive events. This bidirectional communication enables real-time updates and interactions between the client and the server without the need for continuous polling.

Handling Disconnections and Errors: Socket.IO provides mechanisms for handling disconnections and errors gracefully. It automatically attempts to reconnect in case of a connection loss and provides event listeners for error handling.

Additional Features: Socket.IO offers additional features like rooms and namespaces for organizing clients, as well as support for broadcasting messages to multiple clients simultaneously.

Steps To Create Socket Application

  1. First you have to create a Folder and open That folder inside VS code
  2. Open Terminal inside that folder write npm init after installing Packege.JSON created in your Folder.
  3. install npm i express in terminal.
  4. then install socket npm install inside terminal. After installing socket you will see that socket successfully added in your Json File.
  "name": "websocket",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.19.2",
    "": "^4.7.5"

Enter fullscreen mode Exit fullscreen mode

Create a new file eg. app.js
add Socket in the code

const http = require("http");
const express = require("express");
const path = require("path");
const { Server } = require("");

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

io.on('connection', (socket) => {
    console.log('A user connected');

    socket.on("user-message", (message) => {
        console.log('Message received:', message);
        io.emit("Message", message);


app.get("/", (req, res) => {
    return res.sendFile("/public/index.html");

server.listen(9000, () => console.log(`Server started at PORT 9000`));

Enter fullscreen mode Exit fullscreen mode


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat APP</title>

    <input type="text" id="message" placeholder="Enter Message"/>
    <button id="SendBtn">Send</button>

    <div id="messages"></div>

    <script src="/"></script>
        const socket = io();
        console.log('Client connected');

        const sendBtn = document.getElementById('SendBtn');
        const messageInput = document.getElementById('message');
        const allMessages = document.getElementById('messages')

        socket.on("Message", (message) => {
          const p = document.createElement("p");
          p.innerText = message;

        sendBtn.addEventListener("click", () => {
            const message = messageInput.value;
            console.log('Message sent to server:', message);
            socket.emit('user-message', message);
            messageInput.value = ''; // Clear input field after sending

Enter fullscreen mode Exit fullscreen mode

To Run this code node app.js
The Output Will Look Like

Server started at PORT 9000
Enter fullscreen mode Exit fullscreen mode

open two Chrome browsers, split your screen and search for localhost:9000 in both. Then, open the inspect feature and access the console. Write a message in the console and you will notice that it appears in both browsers simultaneously. This is how websocket works.

                 **Thank You**
Enter fullscreen mode Exit fullscreen mode

Top comments (0)