Rumah >hujung hadapan web >tutorial js >WebSockets dan Socket.IO: Komunikasi Masa Nyata dengan Node.js

WebSockets dan Socket.IO: Komunikasi Masa Nyata dengan Node.js

Mary-Kate Olsen
Mary-Kate Olsenasal
2024-10-09 22:46:27598semak imbas

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

Komunikasi masa nyata adalah penting dalam aplikasi moden seperti apl sembang, permainan dalam talian dan alatan kerjasama langsung. WebSockets menyediakan saluran komunikasi dupleks penuh melalui sambungan TCP tunggal, membolehkan pertukaran data antara klien dan pelayan dalam masa nyata. Artikel ini akan menerangkan WebSockets, kes penggunaannya dan cara melaksanakannya dalam Node.js. Selain itu, kami akan menyelami Socket.IO, perpustakaan popular yang memudahkan komunikasi WebSocket, bersama-sama dengan contoh praktikal.

Dalam artikel ini, kami akan membincangkan:

  1. Apakah itu WebSockets?
  2. WebSockets vs HTTP: Perbezaan utama.
  3. Menyediakan pelayan WebSocket dalam Node.js.
  4. Apakah itu Socket.IO, dan mengapa anda perlu menggunakannya?
  5. Menyediakan aplikasi sembang masa nyata menggunakan Socket.IO.
  6. Kes penggunaan untuk WebSockets dan Socket.IO.
  7. Menjamin sambungan WebSocket.

Apakah itu WebSockets?

WebSockets menyediakan protokol komunikasi dua arah yang membolehkan pelayan dan klien menghantar data pada bila-bila masa. Tidak seperti HTTP, di mana pelanggan memulakan semua komunikasi dan meminta data daripada pelayan, WebSockets mendayakan sambungan berterusan, membolehkan kedua-dua pihak bertukar data secara berterusan tanpa mewujudkan semula sambungan.

Ciri-ciri Utama:

  • Kependaman Rendah: Soket Web mempunyai overhed yang lebih rendah berbanding HTTP, kerana sambungan sentiasa terbuka, mengurangkan kependaman.
  • Dupleks Penuh: Kedua-dua pelayan dan pelanggan boleh menghantar dan menerima data secara serentak.
  • Sambungan Berterusan: Setelah diwujudkan, sambungan WebSocket kekal terbuka, tidak seperti HTTP, di mana setiap permintaan membuka sambungan baharu.

WebSockets vs HTTP: Perbezaan Utama

Walaupun kedua-dua protokol dijalankan melalui TCP, ia mempunyai perbezaan yang ketara:

Feature WebSockets HTTP
Connection Persistent, full-duplex Stateless, new connection for each request
Directionality Bi-directional (server and client communicate) Client to server only (server responds)
Overhead Low after connection establishment Higher due to headers with every request
Use Case Real-time applications (chats, games) Traditional websites, API requests
Ciri WebSockets HTTP Sambungan Berterusan, dupleks penuh Sambungan baharu tanpa status untuk setiap permintaan Arah Arah Dwiarah (pelayan dan klien berkomunikasi) Pelanggan kepada pelayan sahaja (pelayan bertindak balas) Overhed Rendah selepas penubuhan sambungan Lebih tinggi disebabkan pengepala dengan setiap permintaan Kes Penggunaan Aplikasi masa nyata (sembang, permainan) Tapak web tradisional, permintaan API

Setting Up a WebSocket Server in Node.js

To create a WebSocket server, Node.js provides a built-in ws library that allows you to create a WebSocket server and establish communication with clients.

Installation:

npm install ws

WebSocket Server Example:

const WebSocket = require('ws');

// Create a WebSocket server on port 8080
const wss = new WebSocket.Server({ port: 8080 });

// Listen for incoming connections
wss.on('connection', (ws) => {
    console.log('Client connected');

    // Send a message to the client
    ws.send('Welcome to the WebSocket server!');

    // Listen for messages from the client
    ws.on('message', (message) => {
        console.log(`Received: ${message}`);
        ws.send(`Echo: ${message}`);
    });

    // Handle connection closure
    ws.on('close', () => {
        console.log('Client disconnected');
    });
});

console.log('WebSocket server running on ws://localhost:8080');

In this example:

  • A WebSocket server is created that listens on port 8080.
  • When a client connects, the server sends a welcome message and listens for messages from the client.
  • The server responds with an echo of the message received from the client.

Client-Side WebSocket:

On the client side, you can connect to the WebSocket server using JavaScript:

const socket = new WebSocket('ws://localhost:8080');

// Event listener for when the connection is established
socket.addEventListener('open', (event) => {
    socket.send('Hello Server!');
});

// Listen for messages from the server
socket.addEventListener('message', (event) => {
    console.log(`Message from server: ${event.data}`);
});

What is Socket.IO, and Why Should You Use It?

Socket.IO is a library that makes WebSocket communication easier by providing:

  • Automatic fallback to long polling if WebSockets aren’t supported.
  • Built-in reconnection and error handling mechanisms.
  • Support for rooms and namespaces, which allow for segmented communication channels.

Installation:

npm install socket.io

Setting Up a Socket.IO Server:

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

// Listen for incoming connections
io.on('connection', (socket) => {
    console.log('New client connected');

    // Listen for messages from the client
    socket.on('message', (msg) => {
        console.log(`Message from client: ${msg}`);
        socket.emit('response', `Server received: ${msg}`);
    });

    // Handle disconnection
    socket.on('disconnect', () => {
        console.log('Client disconnected');
    });
});

// Start the server
server.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
});

In this code:

  • A basic Express server is created, and Socket.IO is integrated to handle real-time communication.
  • The server listens for client connections and responds to any messages sent.

Setting Up a Real-Time Chat Application Using Socket.IO

Let's build a simple real-time chat application using Socket.IO to demonstrate its power.

Server Code:

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
    console.log('A user connected');

    // Broadcast when a user sends a message
    socket.on('chat message', (msg) => {
        io.emit('chat message', msg);
    });

    socket.on('disconnect', () => {
        console.log('User disconnected');
    });
});

server.listen(3000, () => {
    console.log('Listening on *:3000');
});

Client Code (index.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Socket.IO Chat</title>
    <script src="/socket.io/socket.io.js"></script>
</head>
<body>
    <h1>Real-time Chat</h1>
    <ul id="messages"></ul>
    <form id="chatForm">
        <input id="message" autocomplete="off" /><button>Send</button>
    </form>

    <script>
        const socket = io();

        // Listen for incoming chat messages
        socket.on('chat message', (msg) => {
            const li = document.createElement('li');
            li.textContent = msg;
            document.getElementById('messages').appendChild(li);
        });

        // Send chat message
        const form = document.getElementById('chatForm');
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            const message = document.getElementById('message').value;
            socket.emit('chat message', message);
            document.getElementById('message').value = '';
        });
    </script>
</body>
</html>

This simple chat application allows multiple users to connect and exchange messages in real-time. Messages sent by one user are broadcast to all other users connected to the server.

Use Cases for WebSockets and Socket.IO

WebSockets and Socket.IO are perfect for scenarios requiring real-time communication, including:

  • Chat Applications: Real-time messaging is made possible by WebSockets or Socket.IO.
  • Online Gaming: Multiplayer online games where players need to see updates in real-time.
  • Collaborative Editing: Applications like Google Docs use WebSockets to allow multiple users to edit documents simultaneously.
  • Live Dashboards: Real-time updates in dashboards for stock markets, sports scores, etc.

Securing WebSocket Connections

Like HTTP, WebSocket connections should be secured to protect sensitive data. This can be done by using wss:// (WebSocket Secure), which is essentially WebSockets over TLS (Transport Layer Security).

Steps to Secure WebSocket with TLS:

  1. Obtain an SSL Certificate from a Certificate Authority (CA).
  2. Update WebSocket Server to listen on wss:// instead of ws://.
  3. Configure NGINX or another reverse proxy to terminate the SSL and forward traffic to your WebSocket server.

Example NGINX configuration:

server {
    listen 443 ssl;
    server_name yourdomain.com;

    ssl_certificate /etc/ssl/certs/yourdomain.crt;
    ssl_certificate_key /etc/ssl/private/yourdomain.key;

    location / {
        proxy_pass http://localhost:8080;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

This ensures that all WebSocket traffic is encrypted, protecting it from eavesdropping and tampering.

Conclusion

WebSockets and Socket.IO enable real-time communication between clients and servers, which is essential for modern applications requiring instant updates. By implementing WebSocket or Socket.IO-based solutions, you can build responsive and efficient applications such as chat systems, collaborative tools, and live dashboards.

In this article, we've covered the basics of WebSockets, the advantages of using Socket.IO, and how to create real-time applications in Node.js. Additionally, we've explored how to secure WebSocket connections to ensure data safety during transmission.

Mastering these technologies will open up numerous possibilities for building powerful, interactive, and scalable web applications.

Atas ialah kandungan terperinci WebSockets dan Socket.IO: Komunikasi Masa Nyata dengan Node.js. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn