npm install websocket
import WebSocket from 'websocket';
const ws = new WebSocket('ws://localhost:8080');
ws.onmessage = function(event) { const data = event.data; // 处理接收到的数据 };
ws.send('Hello, Server!');
componentWillUnmount() { ws.close(); }
// App.js import React, { useEffect, useState } from 'react'; import WebSocket from 'websocket'; function App() { const [messages, setMessages] = useState([]); const [inputValue, setInputValue] = useState(''); const [ws, setWs] = useState(null); useEffect(() => { const ws = new WebSocket('ws://localhost:8080'); setWs(ws); ws.onmessage = function(event) { const data = event.data; setMessages(prevMessages => [...prevMessages, data]); }; return () => { ws.close(); }; }, []); const handleInput = (event) => { setInputValue(event.target.value); }; const sendMessage = () => { ws.send(inputValue); setInputValue(''); }; return (); } export default App;{messages.map((message, index) => (
- {message}
))}
本文为翻滚的胖子原创文章,转载无需和我联系,但请注明来自猿教程iskeys.com