WebSocket异步导出
WebSocket异步导出
- 1、安装sockjs-client和stompjs
- 2、连接后台
- 3、vite.config.ts 配置反向代理
- 4、导出并实时通信
- 5、 封装WebSocket 文件
- 注册登录(城通网盘)
1、安装sockjs-client和stompjs
import SockJS from 'sockjs-client/dist/sockjs.min.js'
import Stomp from 'stompjs'
2、连接后台
let base_url = '/api/****'
//创建STOMP连接
let socket = new SockJS(sockUrl)
// 获取STOMP子协议的客户端对象
this.stompClient = Stomp.over(socket);
// 心跳发送频率
this.stompClient.heartbeat.outgoing = 60000;
// 心跳接收频率
this.stompClient.heartbeat.incoming = 120000;
// 调用.connect方法连接Stomp服务端进行验证
this.stompClient.connect({}, (frame) => {
console.log('Connected: ' + frame);
// 订阅服务端提供的某个topic 如用户id
this.stompClient.subscribe('/topic/***/' + this.$route.params.id, (frame) => {
console.log('Received message:', JSON.stringify(frame.body));
})
});
3、vite.config.ts 配置反向代理
原因:SockJS 使用https和http 传输
// 服务端渲染
server: {
port: env.VITE_PORT, // 端口号
host: "0.0.0.0",
open: env.VITE_OPEN === 'true',
// 本地跨域代理. 目前注释的原因:暂时没有用途,server 端已经支持跨域
proxy: {
['/api']: {
target: 'http://*****/api',
ws: false,
rewrite: (path) => path.replace(new RegExp(‘^/api‘), ''),
},
}
}
4、导出并实时通信
import WebSocketService from '@/utils/websocket'
const exportLoading = ref(false) //异步导出加载中
const exportData = ref(false) //导出结果提示
// 异步导出
const handleAsynExport = async () => {
exportLoading.value = true
try {
await AsynExportApi.exportSales(queryParams.value)
if (WebSocketService?.stompClient == null) {
// 建立 Websocket连接, /topic/***/${id} 是后端提供的
const destination = `/topic/***/${id}`
WebSocketService.connect(destination, handleMessage)
}
} finally {
setTimeout(() => {
if (!exportData.value) {
ElNotification.error({
title: '提示',
message: '导出失败,请稍后重试'
})
}
exportLoading.value = false
}, 3000)
}
//弹窗下载链接
const handleMessage = (data: any) => {
exportData.value = true
exportLoading.value = false
ElNotification.success({
title: '提示',
message: h('p', null, [
h('span', null, data.fileName + '加载成功,请'),
h(
'a',
{
style: 'color: teal;cursor:pointer;text-decoration: underline;',
onClick: () => {
location.replace(data.filePath)
}
},
'下载'
)
])
})
}
//页面切换后断开连接
useRouter().afterEach(() => {
if (WebSocketService?.stompClient !== null) {
//断开Websocket连接
WebSocketService.disconnect()
}
})
5、 封装WebSocket 文件
下载 :WebSocket 封装 访问密码: 3146