6.1 Khái niệm cơ bản về WebSocket
WebSocket là một giao thức truyền thông cung cấp kênh truyền thông full-duplex qua một kết nối TCP đơn. Nó cho phép truyền dữ liệu hai chiều giữa client và server, khiến nó trở thành lý tưởng cho các ứng dụng cần trao đổi dữ liệu liên tục trong thời gian thực, như chat, trò chơi trực tuyến và hệ thống thông báo.
Ưu điểm của WebSocket
- Kết nối hai chiều: WebSocket cung cấp truyền dữ liệu hai chiều, cho phép server và client gửi tin nhắn cho nhau vào bất kỳ lúc nào.
- Độ trễ thấp hơn: so với các yêu cầu HTTP truyền thống, WebSocket giảm thiểu độ trễ nhờ vào kết nối liên tục.
- Tải trọng server thấp hơn: WebSocket giảm số lượng yêu cầu HTTP, làm giảm tải cho server.
Các thành phần chính của WebSocket
- WebSocket Server: phần server, là phần nhận và xử lý kết nối WebSocket.
- WebSocket Client: phần client, là phần thiết lập kết nối với WebSocket server và trao đổi dữ liệu.
6.2 Làm việc với WebSocket trong JavaScript
Làm việc với WebSocket trong JavaScript được thực hiện thông qua đối tượng WebSocket, cung cấp các phương pháp để thiết lập kết nối, gửi và nhận tin nhắn, cũng như xử lý sự kiện.
Tạo kết nối WebSocket:
const socket = new WebSocket('ws://server.example.com/chat');
Các sự kiện của WebSocket:
open
: xảy ra khi kết nối được thiết lập.message
: xảy ra khi nhận được tin nhắn từ server.error
: xảy ra khi có lỗi.close
: xảy ra khi kết nối bị đóng.
Ví dụ sử dụng WebSocket:
const socket = new WebSocket('ws://server.example.com/chat');
socket.addEventListener('open', (event) => {
console.log('Đã kết nối đến máy chủ WebSocket');
socket.send('Xin chào Server!');
});
socket.addEventListener('message', (event) => {
console.log('Tin nhắn từ server:', event.data);
});
socket.addEventListener('error', (event) => {
console.error('Lỗi WebSocket:', event);
});
socket.addEventListener('close', (event) => {
console.log('Ngắt kết nối từ máy chủ WebSocket');
});
6.3 Ví dụ về WebSocket server trên Node.js
Để tạo một WebSocket server có thể sử dụng thư viện ws trong Node.js.
Cài đặt thư viện:
npm install ws
Ví dụ về WebSocket server:
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 Các sự kiện và phương pháp cơ bản của WebSocket
Sự kiện client:
onopen
: xảy ra khi kết nối WebSocket được thiết lậponmessage
: xảy ra khi nhận được tin nhắn từ serveronclose
: xảy ra khi kết nối WebSocket bị đóngonerror
: xảy ra khi có lỗi WebSocket
Phương pháp client
send(data)
: gửi dữ liệu đến serverclose(code, reason)
: đóng kết nối WebSocket với mã và lý do được chỉ định
Sự kiện server
connection
: xảy ra khi client kết nối với servermessage
: xảy ra khi server nhận được tin nhắn từ clientclose
: xảy ra khi kết nối WebSocket bị đóngerror
: xảy ra khi có lỗi WebSocket
Phương pháp server
send(data)
: gửi dữ liệu đến clientclose(code, reason)
: đóng kết nối WebSocket với mã và lý do được chỉ định
6.5 Ví dụ sử dụng WebSocket
Ví dụ: Chat trong thời gian thực
Phía client:
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Chat</title>
</head>
<body>
<input type="text" id="message" placeholder="Nhập tin nhắn của bạn" />
<button onclick="sendMessage()">Gửi</button>
<div id="chat"></div>
<script>
const socket = new WebSocket('ws://localhost:8080');
const chat = document.getElementById('chat');
socket.onopen = function() {
console.log('WebSocket đã mở.');
};
socket.onmessage = function(event) {
const message = document.createElement('p');
message.textContent = event.data;
chat.appendChild(message);
};
socket.onclose = function() {
console.log('WebSocket đã đóng.');
};
socket.onerror = function(event) {
console.error('Lỗi WebSocket đã thấy:', event);
};
function sendMessage() {
const messageInput = document.getElementById('message');
const message = messageInput.value;
socket.send(message);
messageInput.value = '';
}
</script>
</body>
</html>
Phía server:
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);
// Phát tin nhắn đến tất cả các client đã kết nối
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('Lỗi WebSocket:', error);
});
});
console.log('WebSocket server đang chạy trên ws://localhost:8080');
GO TO FULL VERSION