Komunikasi masa nyata telah menjadi ciri utama aplikasi moden, membolehkan kemas kini segera, pertukaran data langsung dan pengalaman pengguna yang responsif. Teknologi seperti WebSockets dan Socket.IO berada di barisan hadapan dalam interaksi masa nyata. Artikel ini akan menyelidiki konsep WebSockets, cara melaksanakannya dalam Node.js dan cara Socket.IO memudahkan komunikasi masa nyata.
WebSocket ialah protokol komunikasi yang menyediakan saluran komunikasi dupleks penuh melalui satu sambungan TCP. Tidak seperti protokol HTTP, yang beroperasi dalam model tindak balas permintaan, WebSocket membenarkan pelayan dan klien menghantar mesej antara satu sama lain pada bila-bila masa, mengekalkan sambungan terbuka.
Ciri-ciri Utama:
WebSockets sesuai untuk aplikasi yang memerlukan pertukaran data masa nyata dan kependaman rendah:
Node.js menyokong WebSocket secara asli melalui pakej ws, perpustakaan yang ringan dan cekap untuk komunikasi WebSocket.
npm install ws
const WebSocket = require('ws'); // Create a WebSocket server that listens on port 8080 const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', (ws) => { console.log('Client connected'); // When the server receives a message ws.on('message', (message) => { console.log('Received:', message); // Echo the message back to the client ws.send(`Server received: ${message}`); }); // Handle connection close ws.on('close', () => { console.log('Client disconnected'); }); }); console.log('WebSocket server is running on ws://localhost:8080');
const ws = new WebSocket('ws://localhost:8080'); ws.on('open', () => { console.log('Connected to WebSocket server'); // Send a message to the server ws.send('Hello Server!'); }); ws.on('message', (data) => { console.log('Received from server:', data); }); ws.on('close', () => { console.log('Disconnected from server'); });
Server Console: Client connected Received: Hello Server! Client disconnected Client Console: Connected to WebSocket server Received from server: Server received: Hello Server! Disconnected from server
Socket.IO ialah perpustakaan popular yang dibina di atas WebSockets yang memudahkan komunikasi masa nyata. Ia menyediakan abstraksi peringkat lebih tinggi, menjadikannya lebih mudah untuk melaksanakan dan mengurus acara masa nyata. Socket.IO juga menyokong mekanisme sandaran untuk penyemak imbas yang tidak menyokong WebSockets, memastikan keserasian yang luas.
Kelebihan Socket.IO:
npm install socket.io
const http = require('http'); const socketIo = require('socket.io'); // Create an HTTP server const server = http.createServer(); const io = socketIo(server, { cors: { origin: "*", methods: ["GET", "POST"] } }); // Handle client connection io.on('connection', (socket) => { console.log('Client connected:', socket.id); // Listen for 'chat' events from the client socket.on('chat', (message) => { console.log('Received message:', message); // Broadcast the message to all connected clients io.emit('chat', `Server: ${message}`); }); // Handle client disconnect socket.on('disconnect', () => { console.log('Client disconnected:', socket.id); }); }); server.listen(3000, () => { console.log('Socket.IO server running on http://localhost:3000'); });
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Socket.IO Chat</title> </head> <body> <input id="message" type="text" placeholder="Type a message"> <button id="send">Send</button> <ul id="messages"></ul> <script src="/socket.io/socket.io.js"></script> <script> const socket = io('http://localhost:3000'); // Listen for chat messages from the server socket.on('chat', (message) => { const li = document.createElement('li'); li.textContent = message; document.getElementById('messages').appendChild(li); }); // Send message to server when button is clicked document.getElementById('send').addEventListener('click', () => { const message = document.getElementById('message').value; socket.emit('chat', message); }); </script> </body> </html>
Setelah pelayan berjalan dan anda membuka fail HTML dalam berbilang penyemak imbas, mesej yang ditaip dalam satu penyemak imbas akan dihantar ke pelayan dan disiarkan kepada semua pelanggan yang disambungkan.
Strim adalah penting untuk mengendalikan fail besar atau data dalam ketulan daripada memuatkan keseluruhan kandungan ke dalam memori. Ia berguna untuk:
const fs = require('fs'); // Create a readable stream const readStream = fs.createReadStream('largefile.txt', 'utf8'); // Listen to 'data' event to read chunks of data readStream.on('data', (chunk) => { console.log('Reading chunk:', chunk); }); // Listen to 'end' event when the file is fully read readStream.on('end', () => { console.log('File reading complete'); });
As your application grows, scaling becomes necessary to handle increased traffic and ensure high availability. Node.js applications can be scaled vertically or horizontally:
Node.js runs on a single thread, but using the cluster module, you can take advantage of multi-core systems by running multiple Node.js processes.
const cluster = require('cluster'); const http = require('http'); const numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Fork workers for each CPU for (let i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`Worker ${worker.process.pid} died`); }); } else { // Workers can share the same HTTP server http.createServer((req, res) => { res.writeHead(200); res.end('Hello, world!\n'); }).listen(8000); }
WebSockets and Socket.IO offer real-time, bi-directional communication essential for modern web applications. Node.js streams efficiently handle large-scale data, and scaling with NGINX and Node’s cluster module ensures your application can manage heavy traffic. Together, these technologies enable robust, high-performance real-time applications.
위 내용은 WebSocket, Socket.IO 및 Node.js와의 실시간 통신의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!