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項目的目錄結構以下:
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.效果圖以下:
9.本期的分享到了這裏就結束啦,是否是很nice,但願對你有所幫助,讓咱們一塊兒努力走向巔峯!express