6.1 Basic WebSocket Concepts
WebSocket is a communication protocol that provides full-duplex communication channels over a single TCP connection. It allows two-way data transmission between the client and server, making it perfect for applications requiring constant real-time data exchange like chat apps, online games, and notification systems.
Advantages of WebSocket
- Two-way communication: WebSocket provides two-way data transmission, allowing both server and client to send messages to each other anytime.
- Lower latency: Compared with traditional HTTP requests, WebSocket reduces latency thanks to its persistent connection.
- Less load on the server: WebSocket reduces the number of HTTP requests, thus reducing server load.
Main WebSocket Components
- WebSocket Server: The server side that accepts and processes WebSocket connections.
- WebSocket Client: The client side that establishes a connection to the WebSocket server and exchanges data.
6.2 Working with WebSocket in JavaScript
You work with WebSocket in JavaScript using the WebSocket object, which provides methods to establish connections, send and receive messages, and handle events.
Creating a WebSocket connection:
const socket = new WebSocket('ws://server.example.com/chat');
WebSocket Events:
open
: triggers when the connection is established.message
: triggers when a message is received from the server.error
: triggers upon an error.close
: triggers when the connection is closed.
Example of using WebSocket:
const socket = new WebSocket('ws://server.example.com/chat');
socket.addEventListener('open', (event) => {
console.log('Connected to the WebSocket server');
socket.send('Hello Server!');
});
socket.addEventListener('message', (event) => {
console.log('Message from server:', event.data);
});
socket.addEventListener('error', (event) => {
console.error('WebSocket error:', event);
});
socket.addEventListener('close', (event) => {
console.log('Disconnected from WebSocket server');
});
6.3 WebSocket Server Example in Node.js
To create a WebSocket server, you can use the ws library in Node.js.
Installing the library:
npm install ws
WebSocket Server Example:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
console.log('New client connected');
ws.on('message', (message) => {
console.log('Received:', message);
ws.send(`Server says: ${message}`);
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
console.log('WebSocket server is running on ws://localhost:8080');
6.4 Main WebSocket Events and Methods
Client-side events:
onopen
: triggers when the WebSocket connection is establishedonmessage
: triggers when a message is received from the serveronclose
: triggers when the WebSocket connection is closedonerror
: triggers upon a WebSocket error
Client-side methods
send(data)
: sends data to the serverclose(code, reason)
: closes the WebSocket connection with the specified code and reason
Server-side events
connection
: triggers when a client connects to the servermessage
: triggers when the server receives a message from the clientclose
: triggers when the WebSocket connection is closederror
: triggers upon a WebSocket error
Server-side methods
send(data)
: sends data to the clientclose(code, reason)
: closes the WebSocket connection with the specified code and reason
6.5 WebSocket Usage Examples
Example: Real-time Chat
Client-side:
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Chat</title>
</head>
<body>
<input type="text" id="message" placeholder="Enter your message" />
<button onclick="sendMessage()">Send</button>
<div id="chat"></div>
<script>
const socket = new WebSocket('ws://localhost:8080');
const chat = document.getElementById('chat');
socket.onopen = function() {
console.log('WebSocket is open now.');
};
socket.onmessage = function(event) {
const message = document.createElement('p');
message.textContent = event.data;
chat.appendChild(message);
};
socket.onclose = function() {
console.log('WebSocket is closed now.');
};
socket.onerror = function(event) {
console.error('WebSocket error observed:', event);
};
function sendMessage() {
const messageInput = document.getElementById('message');
const message = messageInput.value;
socket.send(message);
messageInput.value = '';
}
</script>
</body>
</html>
Server-side:
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', (ws) => {
console.log('New client connected!');
ws.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);
}
});
});
ws.on('close', () => {
console.log('Client disconnected');
});
ws.on('error', (error) => {
console.error('WebSocket error:', error);
});
});
console.log('WebSocket server is running on ws://localhost:8080');
GO TO FULL VERSION