????????實時通信已成為現代 Web 應用程序(尤其是在聊天應用程序中)不可或缺的功能。實時通信提供了一種強大的方法來實現客戶端和服務器之間的實時雙向通信。在本指南中,我們將逐步講解如何使用React WebSockets構建實時聊天應用程序。
先決條件
在深入研究之前,請確保您具備以下條件:
? 對 React 有基本的了解。
? 您的機器上安裝了 Node.js。
? npm類似或 yarn 的包管理器。
? 熟悉 WebSocket 概念。
步驟 1:設置后端
我們需要一個 WebSocket 服務器來處理實時通信。我們將使用 Node.js 的 ws 包。
1、初始化 Node.js 項目:
mkdir chat-backend ?
cd chat-backend ?
npm init -y ?
2、安裝 ws 包:
npm install ws?
3、創建 WebSocket 服務器:
// server.js ?
const WebSocket = require('ws'); ?
const wss = new WebSocket.Server({ port: 8080 }); ?
wss.on('connection', (ws) => {
? ? console.log('Client connected'); ?
? ? ws.on('message', (message) => {
? ? ? ? console.log(`Received: ${message}`); ?
? ? ? ? // Broadcast the message to all clients
? ? ? ? wss.clients.forEach((client) => {
? ? ? ? ? ? if (client.readyState === WebSocket.OPEN) {
? ? ? ? ? ? ? ? client.send(message); ?
? ? ? ? ? ? }
? ? ? ? });
? ? }); ?
? ? ws.on('close', () => {
? ? ? ? console.log('Client disconnected'); ?
? ? });
}); ?
console.log('WebSocket server running on ws://localhost:8080'); ?
4、運行服務器:
node server.js
第 2 步:設置 React 前端
1、創建一個新的 React 應用:
npx create-react-app chat-frontend ?
cd chat-frontend ?
2、WebSocket安裝 WebSocket 的依賴項:
由于將使用瀏覽器的本機 API,因此不需要額外的依賴項。
步驟3:構建聊天界面
1、創建聊天組件:
// src/components/Chat.js ?
import React, { useState, useEffect, useRef } from 'react'; ?
const Chat = () => {
? ? const [messages, setMessages] = useState([]); ?
? ? const [input, setInput] = useState(''); ?
? ? const ws = useRef(null); ?
? ? useEffect(() => {
? ? ? ? ws.current = new WebSocket('ws://localhost:8080'); ?
? ? ? ? ws.current.onmessage = (event) => {
? ? ? ? ? ? setMessages((prev) => [...prev, event.data]); ?
? ? ? ? }; ?
? ? ? ? return () => {
? ? ? ? ? ? ws.current.close(); ?
? ? ? ? };
? ? }, []); ?
? ? const sendMessage = () => {
? ? ? ? if (input.trim()) {
? ? ? ? ? ? ws.current.send(input); ?
? ? ? ? ? ? setInput(''); ?
? ? ? ? }
? ? }; ?
? ? return (
? ? ? ? <div style={{ padding: '20px', maxWidth: '400px', margin: '0 auto', textAlign: 'center' }}>
? ? ? ? ? ? <h2>Real-Time Chat</h2>
? ? ? ? ? ? <div
? ? ? ? ? ? ? ? style={{
? ? ? ? ? ? ? ? ? ? border: '1px solid #ccc',
? ? ? ? ? ? ? ? ? ? borderRadius: '5px',
? ? ? ? ? ? ? ? ? ? padding: '10px',
? ? ? ? ? ? ? ? ? ? maxHeight: '300px',
? ? ? ? ? ? ? ? ? ? overflowY: 'scroll',
? ? ? ? ? ? ? ? }}
? ? ? ? ? ? >
? ? ? ? ? ? ? ? {messages.map((msg, index) => (
? ? ? ? ? ? ? ? ? ? <div key={index} style={{ textAlign: 'left', margin: '5px 0' }}>
? ? ? ? ? ? ? ? ? ? ? ? {msg}
? ? ? ? ? ? ? ? ? ? </div>
? ? ? ? ? ? ? ? ))}
? ? ? ? ? ? </div>
? ? ? ? ? ? <div style={{ marginTop: '10px' }}>
? ? ? ? ? ? ? ? <input
? ? ? ? ? ? ? ? ? ? type="text"
? ? ? ? ? ? ? ? ? ? value={input}
? ? ? ? ? ? ? ? ? ? onChange={(e) => setInput(e.target.value)}
? ? ? ? ? ? ? ? ? ? style={{
? ? ? ? ? ? ? ? ? ? ? ? padding: '8px',
? ? ? ? ? ? ? ? ? ? ? ? width: '70%',
? ? ? ? ? ? ? ? ? ? ? ? marginRight: '5px',
? ? ? ? ? ? ? ? ? ? ? ? borderRadius: '5px',
? ? ? ? ? ? ? ? ? ? ? ? border: '1px solid #ccc',
? ? ? ? ? ? ? ? ? ? }}
? ? ? ? ? ? ? ? />
? ? ? ? ? ? ? ? <button
? ? ? ? ? ? ? ? ? ? onClick={sendMessage}
? ? ? ? ? ? ? ? ? ? style={{
? ? ? ? ? ? ? ? ? ? ? ? padding: '8px 12px',
? ? ? ? ? ? ? ? ? ? ? ? borderRadius: '5px',
? ? ? ? ? ? ? ? ? ? ? ? border: 'none',
? ? ? ? ? ? ? ? ? ? ? ? backgroundColor: '#007BFF',
? ? ? ? ? ? ? ? ? ? ? ? color: '#fff',
? ? ? ? ? ? ? ? ? ? }}
? ? ? ? ? ? ? ? >
? ? ? ? ? ? ? ? ? ? Send
? ? ? ? ? ? ? ? </button>
? ? ? ? ? ? </div>
? ? ? ? </div>
? ? );
};
export default Chat; ?
2、在您的 App.js 中使用聊天組件:
import React from 'react'; ?
import Chat from './components/Chat'; ?
function App() {
? ? return <Chat />; ?
} ?
export default App; ?
3、啟動 React 應用:
npm start ?
步驟4:測試應用程序
? 在多個選項卡或設備中打開您的 React 應用程序。
? 開始在一個選項卡中輸入消息,并實時觀察它們出現在所有連接的客戶端中!
其他增強功能
為了使應用程序可以投入生產,請考慮:
? 為個性化消息添加用戶身份驗證。
? 集成數據庫來存儲聊天記錄。
? 將 WebSocket 服務器和 React 應用程序部署到 Vercel、Heroku 或 AWS 等平臺。
總結
????????我們利用 WebSockets,使用 React 構建了一個輕量級的實時聊天應用程序。該項目展示了 WebSockets 在動態通信方面的強大功能,它適用于各種應用,例如消息平臺、游戲和實時通知。深入了解 WebSocket 協議,進一步增強您的應用程序!
如果您喜歡此文章,請收藏、點贊、評論,謝謝,祝您快樂每一天。?