一、原生 WebSocket API
import React, { useEffect, useState } from "react";
const MyComponent = () => {
const [socket, setSocket] = useState(null);
const [message, setMessage] = useState("");
useEffect(() => {
const newSocket = new WebSocket("ws://localhost:8080");
newSocket.addEventListener("open", () => {
console.log("WebSocket连接已打开");
});
newSocket.addEventListener("message", (event) => {
setMessage(event.data);
});
newSocket.addEventListener("close", () => {
console.log("WebSocket连接已关闭");
});
newSocket.addEventListener("error", (error) => {
console.log("WebSocket出错:", error);
});
setSocket(newSocket);
return () => {
// 组件卸载时关闭WebSocket连接
if (newSocket) {
newSocket.close();
}
};
}, []);
const sendMessage = () => {
if (socket) {
socket.send("你好,服务器!");
}
};
return (
<div>
<p>收到的消息:{message}</p>
<button onClick={sendMessage}>发送消息</button>
</div>
);
};
export default MyComponent;