Data siaran lan nggabungake WebSocket minangka rong aspek penting kanggo mbangun aplikasi wektu nyata kanthi Node.js. Ing artikel iki, kita bakal njelajah cara nyebarake data lan nggabungake WebSocket kanggo nggawe pengalaman pangguna sing interaktif lan responsif.
Langkah 1: Broadcasting Data saka Server
Kanggo nyebarake data saka server menyang sambungan klien, sampeyan bisa nggunakake cara kaya broadcast
ngirim pesen menyang kabeh sambungan utawa send
ngirim pesen menyang sambungan tartamtu. Punika conto data siaran saka server:
// ... Initialize WebSocket server
// Broadcast data to all connections
function broadcast(message) {
for(const client of clients) {
client.send(message);
}
}
// Handle new connections
server.on('connection',(socket) => {
// Add connection to the list
clients.add(socket);
// Handle incoming messages from the client
socket.on('message',(message) => {
// Broadcast the message to all other connections
broadcast(message);
});
// Handle connection close
socket.on('close',() => {
// Remove the connection from the list
clients.delete(socket);
});
});
Langkah 2: Integrasi WebSocket ing Node.js Aplikasi
Kanggo nggabungake WebSocket menyang Node.js aplikasi, sampeyan kudu nggawe WebSocket sambungan ing kode JavaScript. Iki minangka conto nggabungake WebSocket ing sisih klien aplikasi sampeyan:
// Initialize WebSocket connection from the client
const socket = new WebSocket('ws://localhost:8080');
// Handle incoming messages from the server
socket.onmessage =(event) => {
const message = event.data;
// Process the received message from the server
console.log('Received message:', message);
};
// Send a message from the client to the server
function sendMessage() {
const messageInput = document.getElementById('messageInput');
const message = messageInput.value;
socket.send(message);
messageInput.value = '';
}
Kesimpulan
Kanthi nyebarake data lan nggabungake WebSocket ing Node.js, sampeyan bisa mbangun aplikasi wektu nyata sing interaktif lan responsif. Iki nambah pengalaman pangguna lan mbisakake interaksi wektu nyata antarane aplikasi klien lan server.