Skip to main content

Command Palette

Search for a command to run...

6. Socket.io - Node.JS

Published
3 min read

Socket.IO is a library for real-time, bidirectional, and event-based communication between web clients and servers. It enables features like chat, notifications, live feeds, multiplayer games, etc.

WorkFLow

  1. User submits:
    → React: User submit(emit) the message to the server socket.emit('message', message)

  2. Server receives:
    → Node.js: Now server listen/recieve (on message event) the submitted message and broadcast it to all clients including sender socket.on('message', (msg) => io.emit('message', msg))

  3. All clients get the message:
    → React: Receives or Listen from server, updates UI socket.on('message', (msg) => /* update UI */)

npm install socket.io // in server.js
// Server.js
const express = require('express')

//Step 1 . import server from scoket.io
const {Server} = require('socket.io') //Server: This is the main class from socket.io used to create the WebSocket server
const http = require('http')  //Express runs on top of HTTP, and Socket.IO requires access to the raw HTTP server to hook into it.

const app = express();
const cors = require('cors');
app.use(cors())

// Step 2 . Create server after express
const server = http.createServer(app)  //This wraps your app with a raw HTTP server, allowing Socket.IO to bind onto it.

//Step 3. Create instacne of circuite
const io = new Server(server , {
    cors:{
        origin:"http://localhost:5173",  // fronend url
        methods:["GET" , "POST"],
        credentials:true
    }
})  //new Server(server) creates a Socket.IO server instance and attaches it to your HTTP server.

// Event listener for when a client connects via WebSocket.
// The socket object represents the connected client.
// You can use socket.emit(), socket.on() to send/receive messages.
io.on("connection" , (socket)=>{  // connection is an event
    console.log("User Connected")
    console.log("ID: " , socket.id)
    // socket.emit("welcome" , "Welcome to the server") //emit: same user ko msg jaayga,  here welcomw is a custom event this can be used in fronetend like this : socket.on("welcome" , (msg)=>{clg(msg)})
    // socket.broadcast.emit("welcome" , "Welcome to the server") //Jo socket hai usko nai jaayga msg uske alawa doosre ko jaayga

    socket.on("message" , (msg)=>{  //Listens for 'message' events from the client.              
        console.log(msg)
        // Broadcast the message to all clients
        io.emit('message', msg);  //When a client sends a message: io.emit('message', msg);: Broadcasts the message to all connected clients, including the sender.
    })

    socket.on("disconnect" , ()=>{
        console.log("User Disconnected" , socket.id)
    })
})

PORT = 3000
server.listen(PORT , ()=>{
    console.log(`Server is running at Port no . ${PORT}`)
})
//npm install socket.io-client // in client/react folder
import React, { useState, useEffect } from 'react';
import { io } from 'socket.io-client';

const socket = io('http://localhost:3000'); // Backend URL , Connects the frontend to the backend Socket.IO server.

function Home() {
  const [message, setMessage] = useState(''); //State for the current input.
  const [messages, setMessages] = useState([]); //State for the list of all chat messages.

  useEffect(() => {
    // Listen for messages from server
    socket.on('message', (msg) => {   //Listens for 'message' events from the server. When a message arrives, it updates the messages array.
      setMessages((prev) => [...prev, msg]);
    });

    // Cleanup on unmount
    return () => {   //Removes the event listener when the component unmounts to prevent memory leaks.
      socket.off('message');
    };
  }, []);

  const sendMessage = (e) => {
    e.preventDefault();  //Prevents page refresh on form submit.
    if (message.trim()) {
      socket.emit('message', message);  //1. send the message to the backend server
      setMessage('');
    }
  };
  return (
    <div style={{ maxWidth: 400, margin: "2rem auto", fontFamily: "sans-serif" }}>
      <h2>Socket.IO Chat</h2>
      <div style={{ border: "1px solid #ccc", minHeight: 200, padding: 10, marginBottom: 10 }}>
        {messages.map((msg, idx) => (
          <div key={idx}>{msg}</div>
        ))}
      </div>
      <form onSubmit={sendMessage}>
        <input
          value={message}
          onChange={e => setMessage(e.target.value)}
          placeholder="Type message..."
          style={{ width: "80%" }}
        />
        <button type="submit" style={{ width: "18%" }}>Send</button>
      </form>
    </div>
  );
}
export default Home;