直接上代码,只要vue中级就能懂

	mounted(){ 
		this.initWebSocket(); //页面渲染的时候,对ws进行初始化
	},
		methods:{
			initWebSocket () { 
				this.websock = new WebSocket('ws://localhost:8081');//这个连接ws://固定,后面的根据自己的IP和端口进行改变,我设置监听的就是8081
				this.websock.onmessage = this.websocketonmessage
				this.websock.onerror = this.websocketonerror
				this.websock.onopen = this.websocketonopen
				this.websock.onclose = this.websocketclose
			},
			websocketonopen () { // 连接建立之后执行send方法发送数据,这个和自己的后端沟通好需要传什么数据,我的是要进行token验证
				let token = sessionStorage.getItem('token'); 
				let data = {
					type: "REGISTER",
					data: {token:token}
				}
               // this.websock.send(JSON.stringify(data));
               this.websock.send("connection");
			},
			websocketonerror () { //连接错误
				console.log( 'WebSocket连接失败')
			},
			websocketonmessage (e) { // 数据接收
				console.log(JSON.parse(e.data));
			},
			websocketclose (e) {  // 关闭连接
				console.log('已关闭连接', e)
			},
		},
		destroyed () {
			this.websock.close() // 页面销毁后断开websocket连接
		}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Websocket demos</title>
  <script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
</head>

<body>
  <div id="app">
    <input type="text" v-model.trim="msg" @keyup.enter="echo">
    <button @click="echo">发送</button>
  </div>

  <script>
    /* global Vue, WebSocket */
    var ws = null

    new Vue({
      el: '#app',
      data: {
        msg: ''
      },
      methods: {
        echo: function () {
          if (!this.msg) return
          console.log('WebSocket发送消息: ' + this.msg)
          ws.send(this.msg)
        },
        initWebSocket: function (params) {
          // ws = new WebSocket('wss://echo.websocket.org/')
          ws = new WebSocket("ws://30.30.99.151:9093/websocket");
          // var ws = new WebSocket("ws://localhost:8096/websocket/111405");
          ws.onopen = function (e) {
            console.log('WebSocket已经打开: ')
            console.log(e)
          }
          ws.onmessage = function (e) {
            console.log('WebSocket收到消息: ' + e.data)
          }
          ws.onclose = function (e) {
            console.log('WebSocket关闭: ')
            console.log(e)
          }
          ws.onerror = function (e) {
            console.log('WebSocket发生错误: ')
            console.log(e)
          }
        }
      },
      created: function () {
        this.initWebSocket()
      }
    })
  </script>
</body>
</html>

服务端配置

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8081 });//设置端口

wss.on('connection', function connection(ws) {//对‘conntection’这个串进行监听,当收到这个后,执行下面的操作
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });
    
  //下面是我写的测试数据,按需取吧
  let i = 0;
  let j = 0;
  setInterval(()=>{ //因为模拟实时推送数据,所以用了一个定时器推送
    if(++i >= 5){
      i = i%5;
    }
    let x = parseInt(Math.random()*5+1);
    let data = {"pos_y":400+x,"pos_z":0,"pos_x":300+x,"is_online":true,"team":"红队","userName":"测试00"+i,"userid":"1"+i};
     let datas = {"msg":"成功","code":"000000","data":data,"type":"LOCATION"};
    }     
    ws.send(JSON.stringify(datas)); //发送数据
  },1000);
});
 $ npm install websocket

然后启动服务就可以了:

​ node server.js

Logo

前往低代码交流专区

更多推荐