1、安装依赖
yarn add stompjs
yarn add sockjs-client
2、引入
import Stomp from "stompjs";
import SockJS from "sockjs-client";
3、完整项目代码
// 其实代码本身自带了心跳,但是有点小问题(忘了是什么),最后还是决定自己来监听error并重新发起链接 let socketTimer = null export default { name: "App", data() { return { stompClient: null, }; }, created() { this.initWebsocket(); }, destroyed() { // 页面销毁后记得关闭定时器 clearInterval(socketTimer) this.closeWebsocket(); }, methods: { initWebsocket() { let socket = new SockJS("/socket/ws"); this.stompClient = Stomp.over(socket); this.stompClient.debug = null this.stompClient.connect( { Author: "头部信息" }, // 传递token () => { // 我们是gps项目,通过socket接收gps信息 this.stompClient.subscribe("/topic/gps", (res) => { const row = JSON.parse(res.body) // 处理逻辑 fn(row) }); // 发送信息 this.stompClient.send( "/app/test", {}, JSON.stringify({ user: "user" }) ); }, (err) => { // 监听报错信息,手动发起重连 console.log("socketErr: ", err) if (socketTimer) { clearInterval(socketTimer) } // 10s后重新连接一次 socketTimer = setTimeout(() => { console.log("开始重联") this.initWebsocket(); }, 10000); } ); // this.stompClient.heartbeat.outgoing = 10000;
// 若使用STOMP 1.1 版本,默认开启了心跳检测机制(默认值都是10000ms) // this.stompClient.heartbeat.incoming = 0;
// 客户端不从服务端接收心跳包 }, closeWebsocket() { if (this.stompClient !== null) { this.stompClient.disconnect(() => { console.log("关闭连接"); }); } }, }, };
4、别忘了进行代理
// IP PORT 配置 const baseUrl = process.env.BASEURL if (process.env.NODE_ENV === ‘development‘) { // 实际代理转发表 exports.proxy = { ‘/api‘: { target: baseUrl, ws: true, pathRewrite: { ‘^/api‘: ‘/‘ } }, ‘/socket‘: { target: baseUrl, changeOrigin: true, ws: true, pathRewrite: { ‘^/socket‘: ‘/‘ } }, } } // 改成本地 IP exports.host = process.env.HOST exports.port = process.env.PORT
5、发布至线上之后
location ^~ /socket/ { proxy_pass http://127.0.0.1:1080/; # 增加Upgrade协议头和Connection协议头,使http连接升级到websocket连接 proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }
结尾:在实际使用的过程中,遇到了socket动不动就断开重连的情况,虽然照目前看来不影响使用,但是还是决定使用mqtt