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;
我是about组件你