Setting Up WebSockets with Node and Express

 What are WebSockets?

WebSockets provide a full-duplex communication channel between a client (browser) and a server. Unlike HTTP, which is request-response, WebSockets enable real-time, two-way interactions.


How to Set Up WebSockets with Node and Express

Step 1: Initialize your project

Create a new Node.js project and install dependencies:


bash

Copy

Edit

mkdir websocket-example

cd websocket-example

npm init -y

npm install express ws

express: Web framework for Node.js


ws: WebSocket library for Node.js


Step 2: Create a basic Express server

Create a file called server.js:


javascript

Copy

Edit

const express = require('express');

const http = require('http');

const WebSocket = require('ws');


const app = express();

const port = 3000;


// Serve static files from 'public' folder (for client-side)

app.use(express.static('public'));


// Create HTTP server

const server = http.createServer(app);


// Initialize the WebSocket server instance

const wss = new WebSocket.Server({ server });


// Listen for WebSocket connections

wss.on('connection', (ws) => {

  console.log('New client connected');


  // Listen for messages from the client

  ws.on('message', (message) => {

    console.log(`Received message: ${message}`);


    // Echo the message back to the client

    ws.send(`Server says: ${message}`);

  });


  // Connection close event

  ws.on('close', () => {

    console.log('Client disconnected');

  });


  // Send a welcome message when connected

  ws.send('Welcome to the WebSocket server!');

});


// Start the server

server.listen(port, () => {

  console.log(`Server is listening on http://localhost:${port}`);

});

Step 3: Create a simple client

Create a folder named public and add an index.html file:


html

Copy

Edit

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8" />

  <title>WebSocket Client</title>

</head>

<body>

  <h1>WebSocket Demo</h1>

  <input type="text" id="messageInput" placeholder="Enter message" />

  <button id="sendBtn">Send</button>

  <ul id="messages"></ul>


  <script>

    const ws = new WebSocket(`ws://${window.location.host}`);


    const messagesList = document.getElementById('messages');

    const messageInput = document.getElementById('messageInput');

    const sendBtn = document.getElementById('sendBtn');


    ws.onopen = () => {

      console.log('Connected to server');

    };


    ws.onmessage = (event) => {

      const li = document.createElement('li');

      li.textContent = event.data;

      messagesList.appendChild(li);

    };


    sendBtn.onclick = () => {

      const message = messageInput.value;

      if (message) {

        ws.send(message);

        messageInput.value = '';

      }

    };

  </script>

</body>

</html>

Step 4: Run the server

Start your Node server:


bash

Copy

Edit

node server.js

Open your browser and go to http://localhost:3000. You can now send messages to the server and see responses in real-time!


Summary

Use express for serving your app.


Use ws to add WebSocket support.


The server listens for client connections and messages.


The client can send and receive messages instantly.

Learn MERN Stack Course in Hyderabad

Read More

Caching Data with Redis in Node.js

Using Aggregations in MongoDB

Creating Relationships in MongoDB using Mongoose

API Rate Limiting with Express

Visit Our Quality Thought Training in Hyderabad

Get Directions

Comments

Popular posts from this blog

Understanding Snowflake Editions: Standard, Enterprise, Business Critical

Why Data Science Course?

How To Do Medical Coding Course?