채팅 앱, 온라인 게임, 실시간 협업 도구와 같은 최신 애플리케이션에서는 실시간 커뮤니케이션이 필수적입니다. WebSocket은 단일 TCP 연결을 통해 전이중 통신 채널을 제공하므로 클라이언트와 서버 간에 실시간으로 데이터를 교환할 수 있습니다. 이 기사에서는 WebSocket과 그 사용 사례, Node.js에서 구현하는 방법을 설명합니다. 추가적으로, WebSocket 통신을 단순화하는 인기 라이브러리인 Socket.IO와 실제 예제를 함께 살펴보겠습니다.
이 기사에서 다룰 내용은 다음과 같습니다.
WebSocket은 서버와 클라이언트가 언제든지 데이터를 보낼 수 있는 양방향 통신 프로토콜을 제공합니다. 클라이언트가 모든 통신을 시작하고 서버에서 데이터를 요청하는 HTTP와 달리 WebSocket은 지속적인 연결을 지원하므로 연결을 다시 설정하지 않고도 두 당사자가 지속적으로 데이터를 교환할 수 있습니다.
두 프로토콜 모두 TCP를 통해 실행되지만 상당한 차이점이 있습니다.
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 |
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.
npm install ws
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:
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}`); });
Socket.IO is a library that makes WebSocket communication easier by providing:
npm install socket.io
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:
Let's build a simple real-time chat application using Socket.IO to demonstrate its power.
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'); });
<!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.
WebSockets and Socket.IO are perfect for scenarios requiring real-time communication, including:
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).
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.
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.
以上是WebSockets 和 Socket.IO:與 Node.js 即時通信的詳細內容。更多資訊請關注PHP中文網其他相關文章!