WebSocket, Socket.IO 및 Node.js와의 실시간 통신

Barbara Streisand
풀어 주다: 2024-09-27 22:40:31
원래의
1027명이 탐색했습니다.

WebSockets, Socket.IO, and Real-Time Communication with Node.js

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.

Apakah itu WebSocket?

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:

  • Sambungan Berterusan: WebSocket memastikan sambungan terbuka, mengurangkan keperluan untuk mewujudkan semula sambungan.
  • Komunikasi Dwi Arah: Kedua-dua pelayan dan pelanggan boleh menghantar mesej secara bebas.
  • Latensi Rendah: Memandangkan WebSocket mengekalkan sambungan terbuka, ia menghapuskan overhed permintaan HTTP, mengurangkan kependaman.

Bila hendak menggunakan WebSockets?

WebSockets sesuai untuk aplikasi yang memerlukan pertukaran data masa nyata dan kependaman rendah:

  • Aplikasi sembang (cth., Slack, WhatsApp Web)
  • Kemas kini sukan secara langsung
  • Suapan pasaran saham
  • Alat kerjasama masa nyata (cth., Dokumen Google)

Menyediakan WebSocket dalam Node.js

Node.js menyokong WebSocket secara asli melalui pakej ws, perpustakaan yang ringan dan cekap untuk komunikasi WebSocket.

Langkah 1: Pasang Pakej WebSocket

npm install ws
로그인 후 복사

Langkah 2: Buat Pelayan WebSocket

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');
로그인 후 복사

Penjelasan:

  • Pelayan WebSocket mendengar pada port 8080.
  • Acara sambungan dicetuskan apabila pelanggan menyambung.
  • Acara mesej dicetuskan apabila pelayan menerima data daripada klien, yang kemudiannya bergema kembali.

Langkah 3: Buat Pelanggan WebSocket

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');
});
로그인 후 복사

Output:

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
로그인 후 복사

Apakah itu Socket.IO?

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:

  • Sambungan Semula Automatik: Secara automatik cuba menyambung semula jika sambungan terputus.
  • Ruang nama dan Bilik: Mengatur sambungan ke dalam ruang nama dan bilik, membolehkan komunikasi yang lebih berstruktur.
  • Model dipacu peristiwa: Menyokong acara tersuai, menjadikan komunikasi lebih semantik.

Menggunakan Socket.IO dengan Node.js

Langkah 1: Pasang Socket.IO

npm install socket.io
로그인 후 복사

Langkah 2: Sediakan Pelayan 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');
});
로그인 후 복사

Penjelasan:

  • Pelayan HTTP dibuat dan Socket.IO dilampirkan padanya.
  • Acara sambungan mengendalikan sambungan pelanggan baharu.
  • Acara sembang ialah acara tersuai untuk menghantar mesej sembang dan memancarkan siaran mesej kepada semua pelanggan.

Langkah 3: Buat Pelanggan Socket.IO

<!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>
로그인 후 복사

Output:

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 Node.js

Strim adalah penting untuk mengendalikan fail besar atau data dalam ketulan daripada memuatkan keseluruhan kandungan ke dalam memori. Ia berguna untuk:

  • File Uploads/Downloads: Streams allow you to process data as it’s being uploaded or downloaded.
  • Handling Large Data: Streams are more memory efficient for handling large files or continuous data.

Types of Streams in Node.js:

  1. Readable Streams: Streams from which data can be read (e.g., file system read).
  2. Writable Streams: Streams to which data can be written (e.g., file system write).
  3. Duplex Streams: Streams that can both be read from and written to (e.g., TCP sockets).
  4. Transform Streams: Streams that can modify or transform data as it is written and read (e.g., file compression).

Example: Reading a File Using Streams

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');
});
로그인 후 복사

Scaling Node.js Applications

As your application grows, scaling becomes necessary to handle increased traffic and ensure high availability. Node.js applications can be scaled vertically or horizontally:

  • Vertical Scaling: Increasing the resources (CPU, RAM) of a single machine.
  • Horizontal Scaling: Running multiple instances of your Node.js application across different machines or cores.

Cluster Module in Node.js

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);
}
로그인 후 복사

Conclusion

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿