Web Sockets are a powerful tool for enabling real-time communication between clients and servers. Whether we're building a chat application, a collaborative editor, or a live notification system, Web Sockets can help we deliver fast, bidirectional communication. In this guide, we'll explore how to get started with Web Sockets in Node.js.
What Are Web Sockets?
Web Sockets provide a full-duplex communication channel over a single, long-lived TCP connection. Unlike HTTP requests, which follow a request-response pattern, Web Sockets enable the server to send updates to the client without being explicitly requested.
Prerequisites
Before diving into Web Sockets, ensure we have the following installed:
- Node.js (version 14 or later recommended)
- npm (comes with Node.js)
Setting Up a Node.js Project
Start by initializing a new Node.js project:
mkdir websocket-demo
cd websocket-demo
npm init -y
Install the ws
package, a popular Web Socket library for Node.js:
npm install ws
Creating a Basic Web Socket Server
We'll create a Web Socket server to handle real-time communication.
- Create a new file named
server.js
. - Add the following code:
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', (socket) => {
console.log('New client connected');
// Send a welcome message to the client
socket.send('Welcome to the Web Socket server!');
// Handle incoming messages from the client
socket.on('message', (message) => {
console.log(`Received: ${message}`);
// Broadcast the message to all connected clients
server.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
// Handle client disconnection
socket.on('close', () => {
console.log('Client disconnected');
});
});
console.log('Web Socket server is running on ws://localhost:8080');
Running the Server
Run our Web Socket server using Node.js:
node server.js
We should see the message:
Web Socket server is running on ws://localhost:8080
Creating a Web Socket Client
To test our Web Socket server, create a simple client. We'll separate JavaScript from HTML for better organization.
- Create a file named
index.html
and add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Socket Client</title>
<script src="client.js" defer></script>
</head>
<body>
<h1>Web Socket Client</h1>
<textarea id="messages" rows="10" cols="30" readonly></textarea><br>
<input type="text" id="message" placeholder="Type a message...">
<button id="sendButton">Send</button>
</body>
</html>
- Create a file named
client.js
and add the following code:
const socket = new WebSocket('ws://localhost:8080');
const messages = document.getElementById('messages');
const messageInput = document.getElementById('message');
const sendButton = document.getElementById('sendButton');
socket.onopen = () => {
console.log('Connected to the server');
messages.value += 'Connected to the server\n';
};
socket.onmessage = (event) => {
messages.value += `Server: ${event.data}\n`;
};
socket.onclose = () => {
console.log('Disconnected from the server');
messages.value += 'Disconnected from the server\n';
};
sendButton.addEventListener('click', () => {
const message = messageInput.value;
if (message) {
socket.send(message);
messages.value += `You: ${message}\n`;
messageInput.value = '';
}
});
Testing the Application
- Start the Web Socket server (
node server.js
). - Open the
index.html
file in multiple browser tabs. - Type a message in one tab and send it. The message should appear in all open tabs.
Conclusion
Web Sockets open up a world of possibilities for real-time applications. By setting up a basic Web Socket server and client, we've taken the first step toward building more dynamic and interactive applications. Experiment with different use cases and explore the full potential of Web Sockets in Node.js.
Top comments (0)