WebSockets provide a full-duplex communication channel over a single TCP connection. This technology is particularly useful in applications that require real-time data updates, such as chat applications, live notifications, and online gaming.
To start using WebSockets in Node.js, we will use the ws
library, which is a popular WebSocket implementation. Follow these steps to create a simple WebSocket server:
ws
LibraryFirst, ensure you have Node.js installed on your machine. Then, create a new directory for your project and initialize a new Node.js application:
mkdir websocket-example
cd websocket-example
npm init -y
Now, install the ws
library:
npm install ws
Create a file named server.js
and add the following code:
const WebSocket = require('ws');
// Create a WebSocket server
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
console.log('New client connected');
// Send a welcome message to the newly connected client
ws.send('Welcome to the WebSocket server!');
// Listen for messages from the client
ws.on('message', (message) => {
console.log('Received:', message);
// Echo the message back to the client
ws.send(`You said: ${message}`);
});
// Handle client disconnection
ws.on('close', () => {
console.log('Client disconnected');
});
});
console.log('WebSocket server is running on ws://localhost:8080');
Run your WebSocket server using:
node server.js
You should see the message indicating that the server is running.
To test our WebSocket server, we can create a simple HTML client. Create a file named index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Client</title>
</head>
<body>
<h1>WebSocket Client</h1>
<input type="text" id="messageInput" placeholder="Type a message..."><br>
<button id="sendButton">Send</button>
<div id="messages"></div>
<script>
const ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => {
console.log('Connected to the server');
};
ws.onmessage = (event) => {
const messagesDiv = document.getElementById('messages');
messagesDiv.innerHTML += `<p>${event.data}</p>`;
};
document.getElementById('sendButton').onclick = () => {
const input = document.getElementById('messageInput');
ws.send(input.value);
input.value = '';
};
</script>
</body>
</html>
Open index.html
in a web browser. Type a message into the input field and click the