Lesson 95 – Creating a WebSocket Server and Client in JavaScript
In this lesson, we'll learn how to set up a WebSocket server and connect to it with a client using JavaScript. WebSockets allow for real-time communication between a browser and a server.
What You'll Learn
- Setting up a basic WebSocket server (Node.js)
- Connecting to the WebSocket server from a browser
- Sending and receiving messages
1. Setting Up the WebSocket Server
We’ll use Node.js and the ws
library to create a simple WebSocket server.
Step 1: Initialize a Node.js project
npm init -y
npm install ws
Step 2: Create the server (server.js
)
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', ws => {
console.log('Client connected');
ws.on('message', message => {
console.log(`Received: ${message}`);
ws.send(`Echo: ${message}`); // Echo message back to client
});
ws.on('close', () => console.log('Client disconnected'));
});
2. Creating a WebSocket Client (Browser)
You can connect to the server using browser JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>WebSocket Client</title>
</head>
<body>
<h1>WebSocket Client</h1>
<input id="messageInput" type="text" placeholder="Type a message..." />
<button onclick="sendMessage()">Send</button>
<pre id="chatLog"></pre>
<script>
const socket = new WebSocket('ws://localhost:8080');
const log = document.getElementById('chatLog');
socket.onopen = () => {
log.textContent += "Connected to WebSocket server\n";
};
socket.onmessage = (event) => {
log.textContent += `Server: ${event.data}\n`;
};
function sendMessage() {
const input = document.getElementById('messageInput');
const message = input.value;
socket.send(message);
log.textContent += `You: ${message}\n`;
input.value = '';
}
</script>
</body>
</html>
???? Run the Node.js server first using
node server.js
, then open the HTML file in your browser.
Summary
- A WebSocket server listens for client connections and handles real-time communication.
- The browser connects to the WebSocket and sends/receives messages asynchronously.
- WebSockets are ideal for real-time apps like chats, games, and live updates.
Try It Yourself
- Modify the server to broadcast messages to all connected clients.
- Add a timestamp to messages in the client.
- Handle error events (
socket.onerror
andsocket.onclose
).