2020-09-07

服务端

const WebSocket = require('ws');

function noop() {}
function heartbeat() {
  this.isAlive = true;
}
let port = 8080
const wss = new WebSocket.Server({ port: port });

wss.on('connection', function connection(ws) {
  ws.isAlive = true;
  ws.on('pong', heartbeat);
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
    //ws.send(message);
    wss.clients.forEach(function each(iws) {
      if (iws.isAlive === true) iws.send(message);
    });
  });
  let count = 0;
  wss.clients.forEach(function each(ws) {
    if (ws.isAlive === true) count++;
  });
  console.log("现在有 ", count, " 台设备连接");
});
console.log("Running at http://localhost:", port);

客户端

 data: function() {
    return {
      ws: null
      		}
      	}
      	 methods: {
        stocketOpen(){
        this.ws = new WebSocket('ws://localhost:8080');
    },
    stocketClose(){
      this.ws = null;
      setTimeout(() => {
        this.stocketOpen();
      }, 5000);
    },
    stocketSend(){
      this.ws.onopen = ()=>{
     this.ws.send('发送字符串');
        console.log("已发送")
      }
    }
    }


this.ws.onmessage = (data)=>{
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值