webSocket实现在vue 对应页面接收消息通知处理

断网(心跳检测)

主要是利用websocket定时发送消息,当超过一定时间消息还未发送成功,浏览器的websocket会自动触发onclose方法,而此时onclose有绑定了重连函数,于是就触发websocket重新连接),

const  url = 'ws://127.0.0.1:3000'
class WebSocketClass {
  constructor() {
    this.instance = null;
    this.connect();
  }
  static getInstance() {
    //使用单例模式,只可以被实例化一次
    if (!this.instance) {
      this.instance = new WebSocketClass();
    }
    return this.instance;
  }
  // 创建连接
  connect() {
    if('WebSocket' in window){
      this.ws = new WebSocket(url)
    }else if('MozWebSocket' in window){
      this.ws = new MozWebSocket(url)
    }
    this.ws.onopen = e => {
      this.heartCheck();
      this.getMessage();
    };
  }
  // 心跳
  heartCheck() {
    const _this = this;
    // 心跳状态
    this.state = setInterval(() => {
      // readyState
      // 0 - 表示连接尚未建立。
      // 1 - 表示连接已建立,可以进行通信。
      // 2 - 表示连接正在进行关闭。
      // 3 - 表示连接已经关闭或者连接不能打开。
      if (this.ws.readyState === 1) {
        //发送消息
      	this.ws.send("准备好了,开始吧。。。");
      } else {
        this.closeHandle(); // 重新连接
        console.log("状态未连接");
      }
    }, 60000);
  }
  closeHandle() {
    if (this.state) {
      console.log(`断开,重连websocket`);
      // 清除定时器;
      clearInterval(this.state);
      this.connect(); // 重连
    } else {
      console.log(`websocket手动关闭,或者正在连接`);
    }
  }
  // 接收信息
  getMessage() {
    this.ws.onmessage = e => {
      if (e.data) {  // 接收到消息
        // 自定义全局监听事件
        window.dispatchEvent(new CustomEvent('onmessageWS', {
          detail: {
            data: newsData
          }
        }))
      }
    };
  }
  // 关闭
  close() {
    this.ws.close();
    console.log("关闭连接");
  }
}

export default WebSocketClass;
调用
import WebSocketClass from "@/utils/websocket.js";
// 创建消息连接
const ws = WebSocketClass.getInstance();
在需要使用的页面中添加
mounted () {
	// 添加socket通知监听
	window.addEventListener('onmessageWS', this.getSocketData)
},
methods: {
    // 收到消息处理
	getSocketData (res) {
		console.log(res)
		// ...业务处理
	},
后端实现 node.js
const express = require('express')
const app = express();
// 导入nodejs-websocket模块
const ws = require('nodejs-websocket')

app.get('/test', function (req, res) {
  res.send('测试接口');
})

// 执行websocket连接
ws.createServer(connection => {
  console.log('new connection...')
  //处理客户端发送过来的消息	
  connection.on("text", function (data) {
    console.log("接收到的客户端消息:" + data);
    connection.sendText('今天加餐,想吃什么,随便点。。。。')
  })
  //监听关闭
  connection.on("close", function (code, reason) {
    console.log("Connection closed")
  })
  //监听异常
  connection.on("error", () => {
    console.log('服务异常关闭...')
  })
  // websocket通信端口 端口不能和服务端口一致
}).listen(3000)

app.listen(8085)
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值