vue+node使用websocket

vue+node使用websocket

1.开发环境 vue+node
2.电脑系统 windows10专业版
3.在使用vue+node开发的过程当中,咱们常常会使用到websocket,下面我来分享一下如何使用,但愿对你有所帮助!
4.node项目中终端中输入如下命令:vue

npm install nodejs-websocket

5.在node项目对应的路由中添加以下代码:node

var express = require('express');
var router = express.Router();
var ws = require("nodejs-websocket");
var timer;
var server = ws.createServer(function (conn) {
    console.log("New connection")
    conn.on("text", function (str) {
        clearInterval(timer);
        console.log("接收到客户端发来的消息: " + str)
        // 给客户端发消息
        let a = 1;
        let arr = [
            [20, 21, 22, 23, 20, 20, 18, 26],
            [21.5, 20, 23, 25, 21, 24, 22, 28],
            [22, 26, 35, 27, 26.3, 34, 35, 28],
            [21.5, 20, 37, 29, 21, 27, 22, 28],
            [21.5, 20, 39, 25, 42, 24, 27.5, 28],
            [21.5, 24, 23, 25, 36, 24, 22, 45],
            [21.5, 20, 23, 23, 21, 45, 22, 46],
            [21.5, 27, 23, 35, 21, 37, 22, 28],
            [21.5, 20, 24, 25, 21, 35, 22, 27],
            [21.5, 20, 23, 25, 38, 24, 10, 28]
        ]
        conn.sendText(str)
        timer = setInterval(function () {
            let obj = {
                zao: arr[Math.floor(Math.random() * 10)],
                zhong: arr[Math.floor(Math.random() * 10)],
                wan: arr[Math.floor(Math.random() * 10)],
                a: str + a++
            }
            conn.sendText(JSON.stringify(obj))
        }, 1000);
    })

    conn.on("close", function (code, reason) {
        console.log("Connection closed")
    })
}).listen(8003)
module.exports = router;

6.注意,node项目的目录结构以下:
image.png
7.vue代码以下:web

<template>
  <div class="about">
    <h2>我是about组件你</h2>
  </div>
</template>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
@Component({
  data() {
    return {
      path: "ws://192.168.137.63:8003/users",
      socket: "",
    };
  },
  mounted() {
    let _this: any = this;
    _this.init();
  },
  methods: {
   

    init() {
      var ws = new WebSocket("ws://192.168.137.63:8003/users");
      let _This:any=this;
      ws.addEventListener("open", function (e) {
        console.log("链接成功!");
      });

      ws.onopen = function () {
        console.log("链接成功!");
        ws.send("1");
      };

      ws.onerror = function () {
        console.log("连接错误!");
      };

      ws.onclose = function (e) {
        console.log("断开连接!");
      };

      ws.onmessage=function (msg) {
      console.log("Message from server ", JSON.parse(msg.data));  //输出 后台返回的数据
    };

      // 监听服务端推送过来的消息
      // ws.addEventListener("message", function (event) {
      //   console.log("Message from server ", JSON.parse(event.data));  ////输出 后台返回的数据
      // });
    },
    }
  },
  destroyed() {
    let _this: any = this;
    // 销毁监听
    _this.ws.onclose = _this.close;
  },
})
export default class About extends Vue {}
</script>

8.效果图以下:
image.png
9.本期的分享到了这里就结束啦,是否是很nice,但愿对你有所帮助,让咱们一块儿努力走向巅峰!express

相关文章
相关标签/搜索