To implement a custom WebSocket server using the ws
library in Node.js, you can follow these steps:
Install the ws
library:
Make sure you have Node.js installed on your machine. You can then use npm to install the ws
library:
bashnpm install ws
Create a WebSocket server:
Create a new file (e.g., websocket-server.js
) and implement the WebSocket server using the ws
library:
javascriptconst WebSocket = require('ws');
const server = new WebSocket.Server({ port: 3000 });
server.on('connection', (socket) => {
console.log('Client connected');
// Handle messages from clients
socket.on('message', (message) => {
console.log(`Received message: ${message}`);
// Broadcast the message to all connected clients
server.clients.forEach((client) => {
if (client !== socket && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
// Handle disconnection
socket.on('close', () => {
console.log('Client disconnected');
});
});
console.log('WebSocket server listening on port 3000');
This code creates a WebSocket server listening on port 3000. It logs messages when a client connects, disconnects, and sends a message. It also broadcasts messages to all connected clients.
Run the WebSocket server: Save the file and run it using Node.js:
bashnode websocket-server.js
The WebSocket server will start listening on port 3000.
Create a WebSocket client:
You can create a simple WebSocket client to test the server. Here's an example using JavaScript in an HTML file (websocket-client.html
):
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>
<input type="text" id="messageInput" placeholder="Type a message">
<button onclick="sendMessage()">Send</button>
<ul id="messages"></ul>
<script>
const socket = new WebSocket('ws://localhost:3000');
socket.addEventListener('open', (event) => {
console.log('Connected to WebSocket server');
});
socket.addEventListener('message', (event) => {
const messagesElement = document.getElementById('messages');
const li = document.createElement('li');
li.textContent = event.data;
messagesElement.appendChild(li);
});
function sendMessage() {
const inputElement = document.getElementById('messageInput');
const message = inputElement.value;
socket.send(message);
inputElement.value = '';
}
</script>
</body>
</html>
Open the HTML file in a web browser. You can now type messages in the input field, click the "Send" button, and see the messages being broadcasted to all connected clients.
This example provides a basic implementation of a WebSocket server using the ws
library in Node.js. You can extend and customize it based on your specific requirements.