AskHandle Blog
Building a Node.js WebSocket Server

Building a Node.js WebSocket Server
Creating a WebSocket server with Node.js opens up a world of opportunities for real-time applications. WebSockets provide a persistent connection, allowing for continuous, two-way communication between clients and servers. This article will guide you through setting up a simple WebSocket server in Node.js and offer insights into its usage and benefits.
Getting Started with Node.js
Before diving into WebSockets, ensure you have Node.js installed on your machine. If you don't have it already, you can download it from the official website. Node.js allows you to run JavaScript code on the server, making it a versatile choice for web development.
Once you have Node.js installed, create a new directory for your project and initialize a new Node.js application.
1mkdir websocket-server
2cd websocket-server
3npm init -yThis command will generate a package.json file, which will help manage your project dependencies.
Adding the WebSocket Library
To create a WebSocket server, you'll need a library. A popular choice is ws. Install it by running:
1npm install wsWith this library, you can easily implement WebSocket functionality into your application.
Setting Up the WebSocket Server
Create a file named server.js in your project directory. In this file, you'll set up your WebSocket server. Start by requiring the necessary modules:
1const WebSocket = require('ws');
2const server = new WebSocket.Server({ port: 8080 });This code initializes a WebSocket server that listens on port 8080. You can choose a different port if needed, but ensure it’s free.
Next, add an event listener to handle incoming connections:
1server.on('connection', (socket) => {
2 console.log('New client connected');
3
4 socket.on('message', (message) => {
5 console.log(`Received: ${message}`);
6 // Echo the message back to the client
7 socket.send(`You said: ${message}`);
8 });
9
10 socket.on('close', () => {
11 console.log('Client disconnected');
12 });
13});This snippet logs when a new client connects and handles messages sent by the client. When a message is received, it sends an acknowledgment back.
To finish your server, add the following line:
1console.log('WebSocket server is running on ws://localhost:8080');Running the Socket Server
With all set up, it's time to run your server. Execute the following command in your terminal:
1node server.jsYou'll see a message in the console confirming the server is running. Now, your WebSocket server is ready to accept connections!
Testing Your WebSocket Server
Testing your server can be done using a simple HTML file. Create a new file named index.html in your project directory with the following code:
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>WebSocket Client</title>
7</head>
8<body>
9 <script>
10 const socket = new WebSocket('ws://localhost:8080');
11
12 socket.onopen = () => {
13 console.log('Connected to server');
14 socket.send('Hello, Server!');
15 };
16
17 socket.onmessage = (event) => {
18 console.log(`Message from server: ${event.data}`);
19 };
20
21 socket.onclose = () => {
22 console.log('Disconnected from server');
23 };
24 </script>
25</body>
26</html>Open this file in your web browser. You should see logs in both the browser console and the terminal where you’re running the Node.js server. This interaction showcases the power of real-time communication.
Advantages of WebSocket
Using WebSockets in web applications has several benefits. They maintain a persistent connection, which reduces latency, especially in applications where timely data exchange is critical. Examples include chat applications, gaming, and live notifications. Unlike traditional HTTP requests, WebSockets ensure that both the server and client can send messages at any time, providing a more fluid experience.
Creating a WebSocket server using Node.js is straightforward and can be immensely rewarding. Whether you're building a chat application, real-time collaboration tools, or other interactive features, the WebSocket protocol offers a robust solution for bidirectional communication. With just a few lines of code, you've set the foundation for creating dynamic, real-time experiences. Dive deeper into the WebSocket API and let your creativity guide you in building innovative applications.