vue+node应用websocket

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

npm install nodejs-websocket

5.在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我的项目的目录构造如下:

7.vue代码如下:

<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.效果图如下:

9.本期的分享到了这里就完结啦,是不是很nice,心愿对你有所帮忙,让咱们一起致力走向巅峰!