Before jumping in, make sure you've got:
First off, let's create a new Node.js project. Open up your terminal and run:
mkdir secure-websocket
cd secure-websocket
npm init -y
Next, we need to install some packages. These include ws
for WebSockets, express
for our server, and https
for secure communication:
npm install ws express https
Now, for local testing, we can create self-signed certificates. For a production environment, definitely go with certificates from a trusted Certificate Authority (CA).
To generate self-signed certificates, use OpenSSL:
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
This will produce two files: key.pem
(the private key) and cert.pem
(the certificate).
Time to code our server. Create a new file called server.js
and add this code:
const fs = require('fs');
const https = require('https');
const WebSocket = require('ws');
const express = require('express');
// Load SSL/TLS certificates
const privateKey = fs.readFileSync('key.pem', 'utf8');
const certificate = fs.readFileSync('cert.pem', 'utf8');
const credentials = { key: privateKey, cert: certificate };
// Create an HTTPS server
const app = express();
const httpsServer = https.createServer(credentials, app);
// Initialize WebSocket server instance
const wss = new WebSocket.Server({ server: httpsServer });
// Define WebSocket server behavior
wss.on('connection', (ws) => {
console.log('A client connected.');
// Respond to client messages
ws.on('message', (message) => {
console.log('Received:', message);
ws.send(`Server received: ${message}`);
});
// Handle connection closure
ws.on('close', () => {
console.log('A client disconnected.');
});
// Send a welcome message
ws.send('Welcome to the secure WebSocket server!');
});
// Start the HTTPS server
httpsServer.listen(443, () => {
console.log('HTTPS server running on port 443');
});
Next, let's build our client. Create an HTML 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>Secure WebSocket Client</title>
</head>
<body>
<h1>Secure WebSocket Client</h1>
<input type="text" id="messageInput" placeholder="Enter message">
<button id="sendButton">Send</button>
<div id="messages"></div>
<script>
const ws = new WebSocket('wss://localhost');
ws.onopen = () => {
console.log('Connected to the WebSocket server');
addMessage('Connected to the WebSocket server');
};
ws.onmessage = (event) => {
console.log('Received:', event.data);
addMessage(event.data);
};
ws.onclose = () => {
console.log('Disconnected from the WebSocket server');
addMessage('Disconnected from the WebSocket server');
};
const sendBtn = document.getElementById('sendButton');
const messageInput = document.getElementById('messageInput');
const messagesDiv = document.getElementById('messages');
sendBtn.addEventListener('click', () => {
const message = messageInput.value;
ws.send(message);
addMessage(`You: ${message}`);
messageInput.value = '';
});
function addMessage(message) {
const p = document.createElement('p');
p.textContent = message;
messagesDiv.appendChild(p);
}
</script>
</body>
</html>
In the terminal, navigate to your project directory and start the server with:
node server.js
You should see a message indicating the server is running.
To serve the index.html
file, you can use a simple HTTP server. The http-server
package comes in handy here:
npx http-server -o
This command will serve the HTML file and open it in your default browser.
By following this guide, you'll have a secure WebSocket communication channel between your client and server. This way, your data stays safe and sound while benefiting from the amazing real-time capabilities of WebSockets.