websocket-client-sever
v1.0.0
Published
websocket client component
Downloads
3
Readme
这是一个websocket连接封装:
使用方式如下 引入后:
const ws = new WebSocketClient(url, token);
useEffect(() => {
// 链接websocket
ws.onOpen(() => {
console.log('WebSocket connection opened', new Date());
// do something when the WebSocket connection is opened
setInterval(() => {
ws.onHeartbeat();
}, 3000);
});
// 心跳包
ws.onClose((event) => {
console.log(
`WebSocket connection closed with code ${event.code} and reason ${event.reason}`,
new Date(),
);
// do something when the WebSocket connection is closed
});
ws.onError((event) => {
console.log('WebSocket error:', event, new Date());
// do something when there is a WebSocket error
});
ws.onMessage((res) => {
console.log('WebSocket message received:', res.data);
// sendSocketMessage(msg)
});
ws.connect(); // connect to the WebSocket server
return () => {
ws.disconnect(); // disconnect from the WebSocket server
};
}, []);