websocket连接成功建立以后前台的onmessage不会自动触发,为什么?

前端:vue
后台:node

如题,websocket已经成功连接,readystate状态码是1(已建立连接可通讯的意思),后台向前台推送的数据其实是可以接收到的,但是只能靠我手动刷新页面,他才会调用一次onmessage回调方法,没有办法实时接收到数据,这是为啥,求大神指点QAQ

前端代码:

// 建立通讯
    initWebSocket () {
        var that = this
        ws = new WebSocket('ws://localhost:8081')
        ws.onopen = function () {
          that.socketOpen()
        }
        ws.onmessage = function (data) {
          that.socketMsg(data)
        }
        ws.onclose = function (e) {
          that.socketClose(e)
        }
        ws.onerror = function (err) {
          console.log(err)
        }
    },
    socketMsg (data) {
        console.log(JSON.parse(data.data))
    }

node后台(设置定时器,查表后定时向前台推送):

var WebSocketServer = require('ws').Server,
    wss = new WebSocketServer({ port: 8081 });
wss.on('connection', function (ws) {
    console.log('client connected');
    saleRecord();
});

var time = setTimeout(saleRecord, 5000);
function saleRecord () {
    db.select(connection, sql, function (res) {
       // ...
       wss.on('connection', function (ws) {
          // ...
          ws.send(JSON.stringify(data));
       });
    });
    clearTimeout(time);
    setTimeout(saleRecord, 5000);
}
查看全部
gufeifei_
gufeifei_
2019/03/13 14:37
  • node.js
  • vue.js
  • 点赞
  • 收藏
  • 回答
    私信

0个回复