需求:使用websocket不借助插件实现发布,订阅,网络断开重连,单点登录后挤号的功能
实现:在用户登录之后获取到token令牌并且存入到本地,可以判断token令牌是否失效来让用户退出登录,websocket的操作是让用户登录后连接到websocket并且发送指令,这边发送的指令是后端给的,之后前端进行接受消息,如果消息是退出登录的直接让他清空本地并且跳转到登录页就行
1.登录获取token令牌并且存储到localStorage
2.在layout也就是页面主体框架拿到token并且去连接websocket
3.连接成功后直接发送指令,之后再去监听返给前端的消息之后实现退出操作
url = `${protocol}://websocket的地址,要后端给?token=${token}`;,
这个我举个例子,连接地址应该是这样的:ws://127.0.0.1:8080?token=362466325,
ws.send(`msg:${this.data.id}`);这个也是后端定的要把账户的id给他,这样去监听登录
重连,之后消息返回loginOut后做退出登录的操作,如果链接因为各种原因关闭了,直接去请求重连。
retryCount: 0,
maxRetryCount: 5,
retryInterval: 2000, // 重试间隔时间,单位:毫秒
注意!!websocket不能设置请求头携带token好像,试了很多次都不行,用ws插件也不行,只能拼接token给后端了,有更好的方法可以在评论区联系我
- let ws;
- let url = "";
- export default {
- mounted() {
- this.connectWebsocket();
- },
- methods: {
- connectWebsocket() {
- let protocol = "ws";
-
- if (typeof WebSocket === "undefined") {
- console.log("您的浏览器不支持WebSocket");
- return;
- } else {
- if (window.location.protocol == "https:") {
- protocol = "wss";
- }
- let token = localStorage.getItem("token");
- url = `${protocol}://websocket的地址,要后端给?token=${token}`;
- // 打开一个ws
- ws = new WebSocket(url);
- ws.onopen = () => {
- // 发送数据
- console.log("ws已连接!!");
- ws.send(`msg:${this.data.id}`);
- // this.$message.success("ws已连接!!");
- };
- // 发生错误时
- ws.onerror = (evt) => {
- console.log("ws错误:", evt);
- };
- // 关闭连接
- ws.onclose = (event) => {
- console.warn("WebSocket 已关闭");
- console.log("关闭代码:", event.code);
- console.log("关闭原因:", event.reason);
- // 处理连接断开事件
- this.handleWebSocketClose();
- };
- ws.onmessage = (evt) => {
- if (evt.data == "loginOut") {
- // 此时要做清空数据的操作
- this.$message.warning("您的帐号在另一地点登录,您已被迫下线!!");
- this.$router.replace("/");
- localStorage.clear();
- ws.close();
- ws.onclose = () => {
- console.log("ws断开连接成功");
- };
- }
- console.log(evt, "接收到的消息");
- };
- this.$bus.$emit("Websocket", ws);
- }
- },
- handleWebSocketClose() {
- if (this.retryCount < this.maxRetryCount) {
- console.log(`正在尝试第 ${this.retryCount + 1} 次重连...`);
- setTimeout(() => {
- this.connectWebsocket();
- this.retryCount++;
- }, this.retryInterval);
- } else {
- console.error("WebSocket 连接失败,已达到最大重试次数");
- }
- },
- }
- }
注意!!这边每次发布的时候都应该重新连一个新的消息,不然和之前的登录的消息搞混了就不好了,特别是在做操作的时候,比如el-table的编辑操作这些,每次关闭弹窗肯定要关闭websocket,如果和登录的消息搞混了,关闭弹窗就不能实时接收到单点登录传来的消息了
这个connectWebsocket和上面的不是一个,这个是需要实时推送页面的websocket连接,不会影响全局的单点登录的。
- let websocket;
- let url = "";
- export default {
- connectWebsocket(data) {
- let protocol = "ws";
-
- if (typeof WebSocket === "undefined") {
- console.log("您的浏览器不支持WebSocket");
- return;
- } else {
- if (window.location.protocol == "https:") {
- protocol = "wss";
- }
- let token = localStorage.getItem("token");
- url = `${protocol}://后端的给的地址?token=${token}`;
- // 打开一个websocket
- websocket = new WebSocket(url);
- websocket.onopen = () => {
- // 发送数据
- // console.log("websocket已连接!!");
- websocket.send(data);
- this.$message.success("websocket已连接!!");
- };
- // 发生错误时
- websocket.onerror = (evt) => {
- console.log("websocket错误:", evt);
- };
- // 关闭连接
- websocket.onclose = (event) => {
- console.warn("WebSocket 已关闭");
- console.log("关闭代码:", event.code);
- console.log("关闭原因:", event.reason);
- // 处理连接断开事件
- this.handleWebSocketClose(data);
- };
- }
- },
- handleWebSocketClose(data) {
- if (this.retryCount < this.maxRetryCount) {
- console.log(`正在尝试第 ${this.retryCount + 1} 次重连...`);
- setTimeout(() => {
- this.connectWebsocket(data);
- this.retryCount++;
- }, this.retryInterval);
- } else {
- this.$message.error("WebSocket 连接失败!!");
- console.error("WebSocket 连接失败,已达到最大重试次数");
- }
- },
- }
1.点击编辑后打开并且实时接收
- updData(row) {
- this.connectWebsocket(`data_imei:${row.id}`);
- websocket.onmessage = (evt) => {
- //如果收到的消息是msgUpd
- if(evt.data=='msgUpd'){
- let data = JSON.parse(evt.data);
- //把得到的数据进行json转换之后再给tableData进行展示就行
- let tableData.unshift(data)
- //也不能一直接受吧,那数据得多少啊,定义一下接收到多少条后截取
- if (tableData.length > 500) {
- tableData.splice(500);
- }
- }
- }
- }
2.关闭弹窗后需要断开连接
- closeWebSocket() {
- if (websocket != null) {
- websocket.close();
- websocket.onclose = () => {
- console.log("websocket断开连接成功");
- };
- }
- },
3.在离开websocket推送页面后也关闭连接
- destroyed() {
- if (websocket != null) {
- websocket.close();
- websocket.onclose = () => {
- console.log("websocket断开连接成功");
- };
- }
- },
文章到此结束,希望对你所有帮助~~