Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Building Real-time Applications with Node.js and WebSocket

Introduction

Real-time applications are becoming increasingly popular due to their ability to provide immediate feedback and updates. Node.js, with its non-blocking architecture, is an excellent choice for building these applications. WebSocket is a protocol that allows for persistent connections between clients and servers, enabling real-time data transfer.

What is WebSocket?

WebSocket is a communication protocol that provides full-duplex communication channels over a single TCP connection. It is designed to be used in real-time web applications.

  • Full-duplex communication: Allows simultaneous two-way communication.
  • Reduced latency: Lower communication overhead compared to HTTP.
  • Persistent connection: Maintains an open connection for real-time communication.

Setting Up Node.js

To get started with Node.js and WebSocket, ensure you have Node.js installed. You can download it from the official Node.js website.

After installation, create a new directory for your project and run the following command to initialize a new Node.js project:

npm init -y

Next, install the ws library, which is a simple WebSocket library for Node.js:

npm install ws

Creating a WebSocket Server

Now that you have Node.js and the necessary library set up, you can create a simple WebSocket server. Create a file named server.js and add the following code:


const WebSocket = require('ws');

const server = new WebSocket.Server({ port: 8080 });

server.on('connection', (socket) => {
    console.log('New client connected');

    socket.on('message', (message) => {
        console.log(`Received: ${message}`);
        // Echo the message back to the client
        socket.send(`You said: ${message}`);
    });

    socket.on('close', () => {
        console.log('Client disconnected');
    });
});

console.log('WebSocket server is running on ws://localhost:8080');
        

Client Connection

To connect to your WebSocket server, you can use the following HTML code. Create a file named client.html:





    
    WebSocket Client