Buatkan kode node wss agar tidak close
- User
Buatkan kode node wss agar tidak close
- Assistant
Berikut adalah contoh kode Node.js untuk membuat koneksi WebSocket (wss) agar tidak ditutup (close):
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); // Fungsi untuk menjaga koneksi tetap terbuka function heartbeat() { this.isAlive = true; } wss.on('connection', (ws) => { // Set properti isAlive menjadi true ketika ada koneksi baru ws.isAlive = true; ws.on('pong', heartbeat); ws.on('message', (message) => { console.log('Received message:', message); // Lakukan tindakan yang diperlukan berdasarkan pesan yang diterima }); ws.on('close', () => { console.log('Connection closed'); // Lakukan tindakan yang diperlukan saat koneksi ditutup }); }); // Fungsi untuk mengirim pesan ping ke semua koneksi aktif function sendPing() { wss.clients.forEach((ws) => { if (ws.isAlive === false) { console.log('Connection lost'); return ws.terminate(); } ws.isAlive = false; ws.ping(); }); } // Set interval untuk mengirim pesan ping setiap 30 detik const interval = setInterval(sendPing, 30000); // Handle saat server ditutup wss.on('close', () => { clearInterval(interval); });
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.