要構(gòu)建一個實時聊天應用,需使用Node.js和WebSocket實現(xiàn)全雙工通信,具體步驟如下:1. 初始化Node.js項目並安裝ws庫,創(chuàng)建server.js文件,設置WebSocket服務器監(jiān)聽8080端口,維護客戶端連接集合,並在收到消息時廣播給所有客戶端;2. 創(chuàng)建index.html前端頁面,包含消息顯示區(qū)、輸入框和發(fā)送按鈕,通過JavaScript建立與WebSocket服務器的連接,接收消息時動態(tài)添加到頁面,並支持點擊發(fā)送或按Enter鍵提交;3. 修改server.js以集成HTTP服務器功能,使用Node.js內(nèi)置的http、fs和path模塊讀取並響應index.html文件請求,使同一服務器既能提供網(wǎng)頁又能處理WebSocket連接;4. 啟動服務器後,在多個瀏覽器標籤中訪問http://localhost:8080,任意標籤發(fā)送的消息會實時同步到其他標籤。至此,一個基礎但功能完整的實時聊天應用已實現(xiàn),後續(xù)可擴展暱稱、時間戳、私聊、重連機制和輸入淨化等特性。該方案以簡潔代碼展示了實時通信核心機制,為更複雜應用打下基礎。

Building a real-time chat app with WebSockets and Node.js is a practical way to learn full-duplex communication on the web. Unlike traditional HTTP, where the client requests and the server responds, WebSockets allow both sides to send data at any time—perfect for instant messaging.

Here's how to build a simple but functional real-time chat app using Node.js and the ws
library.
1. Set Up the Node.js Server with WebSockets
Start by initializing a Node.js project and installing the ws
package:

npm init -y
npm install ws
Create a file called server.js
. This will handle WebSocket connections and message broadcasting.
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
const clients = new Set();
wss.on('connection', (ws) => {
clients.add(ws);
console.log('Client connected');
ws.on('message', (data) => {
// Broadcast message to all connected clients
for (let client of clients) {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
}
});
ws.on('close', () => {
clients.delete(ws);
console.log('Client disconnected');
});
});
console.log('WebSocket server is running on ws://localhost:8080');
This server listens on port 8080, keeps track of connected clients, and broadcasts any received message to all of them.

2. Create a Simple Frontend HTML Page
Create an index.html
file to serve as the chat interface.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Real-Time Chat</title>
<style>
#messages { height: 300px; overflow-y: scroll; border: 1px solid #ccc; margin-bottom: 10px; padding: 10px; }
#input { width: 80%; padding: 10px; }
#send { width: 15%; padding: 10px; }
</style>
</head>
<body>
<h2>Chat Room</h2>
<div id="messages"></div>
<input type="text" id="input" placeholder="Type a message..." />
<button id="send">Send</button>
<script>
const socket = new WebSocket('ws://localhost:8080');
const messages = document.getElementById('messages');
const input = document.getElementById('input');
const sendButton = document.getElementById('send');
// Display incoming messages
socket.onmessage = (event) => {
const message = document.createElement('div');
message.textContent = event.data;
messages.appendChild(message);
messages.scrollTop = messages.scrollHeight;
};
// Send message on button click or Enter key
sendButton.onclick = () => {
if (input.value.trim()) {
socket.send(input.value);
input.value = '';
}
};
input.addEventListener('keypress', (e) => {
if (e.key === 'Enter') sendButton.click();
});
</script>
</body>
</html>
This page connects to the WebSocket server, displays received messages, and sends user input when the "Send" button is clicked or Enter is pressed.
3. Serve the HTML File
The current server only handles WebSocket connections. To serve index.html
, you need an HTTP server. Update server.js
to include static file serving:
const http = require('http');
const fs = require('fs');
const path = require('path');
const WebSocket = require('ws');
// Create HTTP server
const server = http.createServer((req, res) => {
if (req.url === '/') {
fs.readFile(path.join(__dirname, 'index.html'), (err, data) => {
if (err) {
res.writeHead(500);
res.end('Error loading index.html');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
} else {
res.writeHead(404);
res.end();
}
});
// Attach WebSocket server to the same port
const wss = new WebSocket.Server({ server });
const clients = new Set();
wss.on('connection', (ws) => {
clients.add(ws);
console.log('Client connected');
ws.on('message', (data) => {
for (let client of clients) {
if (client.readyState === WebSocket.OPEN) {
client.send(data.toString());
}
}
});
ws.on('close', () => {
clients.delete(ws);
console.log('Client disconnected');
});
});
server.listen(8080, () => {
console.log('Server running on http://localhost:8080');
});
Now the same server serves the webpage and handles WebSocket connections.
4. Run and Test the App
Start the server:
node server.js
Open multiple browser tabs to http://localhost:8080
Type a message in one tab—it should appear instantly in all others
You now have a working real-time chat app.
Optional Improvements
To make this more robust, consider adding:
- User nicknames : Send metadata along with messages
- Message timestamps : Format and display when messages were sent
- Private messaging : Route messages to specific clients using IDs
- Reconnection logic : Handle network drops gracefully
- Input sanitization : Prevent XSS by escaping HTML in messages
That's it. With just a few dozen lines of code, you've built a real-time chat app using WebSockets and Node.js. The core idea—broadcasting messages to all connected clients—is the foundation of most chat systems. From here, you can scale up with rooms, authentication, or databases. Basically, this is the minimal viable version that actually works.
以上是使用WebSocket和Node.js構(gòu)建實時聊天應用的詳細內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!