node.js使用vue-native-websocket实现websocket通信 实测有效
Vue2、websocket 与node.js接口 本地测试
1. 安装vue-native-websocket模块
2. yarn add vue-native-websocket
或者用
npm install vue-native-websocket --save
3. 在main.js中引入websocket
项目中main.js使用如下图
封装websocket的api
参考https://blog.csdn.net/m0_38134431/article/details/105794108
我自己封装的
let ws = null
let messageCallback = null //ws返回成功的回调函数
let setIntervalWS = null
// 初始化websocket
function initWebSocket(url) {
if (!ws) {
ws = new WebSocket(url)
ws.onmessage = function (e) {
websocketOnmessage(e)
}
ws.onopen = function () {
websocketOpen()
}
ws.onclose = function (e) {
websocketClose(e)
}
ws.onerror = function () {
websocketError()
}
}
}
// 发送数据
function websocketSend(agentData) {
// 添加状态判断
//OPEN时,发送消息
if (ws.readyState === ws.OPEN) {
setIntervalWS = setInterval(() => {
ws.send(JSON.stringify(agentData)) // 发给后端的数据需要字符串化
}, 1000)
//CLOSED时,尝试重连,重连成功,继续发送消息
} else if (ws.readyState === ws.CLOSED) {
retry()
//重连成功,则继续发送
if (ws.readyState === ws.OPEN) {
setIntervalWS = setInterval(() => {
ws.send(JSON.stringify(agentData)) // 发给后端的数据需要字符串化
}, 1000)
}
}
}
// 返回数据
function websocketOnmessage(e) {
messageCallback(JSON.parse(e.data))
}
// 建立连接
function websocketOpen(e) {
console.log('ws连接建立')
}
// 连接失败
function websocketError() {
console.log('ws连接失败,尝试重连')
clearInterval(setIntervalWS)
ws.close()
initWebSocket(url)
}
// 关闭连接
function websocketClose(e) {
clearInterval(setIntervalWS)
ws.close()
ws = null
}
// 重连函数
function retry() {
let maxRetry = 5;
if (maxRetry == 0 || ws != null) {
clearInterval(setIntervalWS)
return false
}
//每3秒一次重连,最多5次
setIntervalWS = setInterval(() => {
ws.onerror()
}, 3000)
}
/**
* 发起websocket请求函数
* @param {type} 0为心跳,1为单次 发送数据的模式
* @param {string} url ws连接地址
* @param {Object} agentData 传给后台的参数
* @param {function} successCallback 接收到ws数据,对数据进行处理的回调函数
*/
export function sendWebsocketPing(type, url, agentData, successCallback) {
initWebSocket(url)
messageCallback = successCallback
switch (type) {
case 0:
websocketSend(agentData)
break;
case 1:
ws.send(agentData)
break;
default:
break;
}
}
/**
* 关闭websocket函数
*/
export function closeWebsocket() {
if (ws) {
ws.onclose() // 关闭websocket
console.log('ws连接关闭')
}
}
新建server.js文件,用于写node.js接口,
安装nodejs-websocket模块npm install websocket
用cmd或者git bash进入项目目录,然后命令行输入node server.js,启动后台服务。文件如下:
var WebSocketServer = require('websocket').server;
var http = require('http');
var json = require('./myTest')
var str1 = "{\"action\": \"stat.nodes\", \"time\": 1590035916, \"data\": {\"nodes\": [{\"fd\": 19, \"ip\": \"192.168.10.11\", \"port\": 55296, \"allow\": true, \"down\": false, \"nodeName\": \"itv-auth-node-138121\", \"mainPort\": 8088, \"group\": \"hot\", \"targetUrl\": \"http://auth.liaowo.test\", \"version\": \"dev - 0\", \"runtime\": \"php: 7.3.18-1+ubuntu18.04.1+deb.sury.org+1, swoole: 4.5.1\", \"weights\": 0.0221}, {\"fd\": 233, \"ip\": \"角卷绵芽\", \"port\": 520, \"allow\": true, \"down\": false, \"nodeName\": \"咚咚咚\", \"mainPort\": 520, \"group\": \"hot\", \"targetUrl\": \"不是我的错吧\", \"version\": \"dev - 0\", \"runtime\": \"php: 7.3.18-1+ubuntu18.04.1+deb.sury.org+1, swoole: 4.5.1\", \"weights\": 0.0221}], \"dispatch_weights\": [{\"fd\": 19, \"weight\": 9997}], \"dispatch_count\": []}}";
var str2 = "{\"action\":\"stat.server\",\"time\":1590045218,\"data\":{\"info\":{\"name\":\"itv-auth-lb-138122\",\"version\":\"dev\",\"build_date\":\"0\",\"runtime_info\":\"php: 7.3.14-6+ubuntu16.04.1+deb.sury.org+1, swoole: 4.4.18\"},\"stat\":{\"server\":{\"start_time\":1590045183,\"connection_num\":2,\"accept_count\":3,\"close_count\":1,\"worker_num\":2,\"idle_worker_num\":1,\"tasking_num\":0,\"request_count\":31,\"worker_request_count\":1,\"worker_dispatch_count\":0,\"coroutine_num\":2},\"worker\":[{\"event_num\":8,\"signal_listener_num\":0,\"aio_task_num\":0,\"aio_worker_num\":2,\"c_stack_size\":2097152,\"coroutine_num\":2,\"coroutine_peak_num\":2,\"coroutine_last_cid\":191,\"pid\":5197,\"timer\":2,\"mem_usage\":3895688,\"mem_peak_usage\":3960464,\"stat_redis\":{\"consumer_num\":0,\"producer_num\":0,\"queue_num\":0,\"create\":0,\"max\":4,\"min\":0},\"http_pool\":null},{\"event_num\":6,\"signal_listener_num\":1,\"aio_task_num\":0,\"aio_worker_num\":2,\"c_stack_size\":2097152,\"coroutine_num\":4,\"coroutine_peak_num\":5,\"coroutine_last_cid\":166,\"pid\":5194,\"timer\":6,\"mem_usage\":3997240,\"mem_peak_usage\":4067208,\"stat_redis\":{\"consumer_num\":0,\"producer_num\":0,\"queue_num\":1,\"create\":1,\"max\":4,\"min\":0},\"http_pool\":null},{\"event_num\":8,\"signal_listener_num\":0,\"aio_task_num\":0,\"aio_worker_num\":2,\"c_stack_size\":2097152,\"coroutine_num\":4,\"coroutine_peak_num\":4,\"coroutine_last_cid\":292,\"pid\":5196,\"timer\":4,\"mem_usage\":5784680,\"mem_peak_usage\":6049248,\"stat_redis\":{\"consumer_num\":0,\"producer_num\":0,\"queue_num\":0,\"create\":0,\"max\":4,\"min\":0},\"http_pool\":null}],\"auth\":{\"accept\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"refuse\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"accept_m3u8\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"accept_ts\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"upstream_err\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"not_found\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"other_err\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"expired\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"invalid_sign\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"bad_ip\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"bad_self\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"bad_sess\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"bad_sign\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"secret_url\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"redis_err\":{\"count\":0,\"qps\":0,\"qps_peak\":0}},\"os\":{\"network\":{\"enp0s8\":{\"rx_bytes\":7479.24,\"tx_bytes\":19874.42,\"load_up\":0.03,\"load_down\":0.01,\"load\":0.02,\"load_wa\":0.02},\"enp0s3\":{\"rx_bytes\":0,\"tx_bytes\":0,\"load_up\":0,\"load_down\":0,\"load\":0,\"load_wa\":0},\"enp0s9\":{\"rx_bytes\":2414.68,\"tx_bytes\":182.16,\"load_up\":0,\"load_down\":0,\"load\":0,\"load_wa\":0}},\"disk\":{\"sdb\":{\"tps\":0,\"rkByteSec\":0,\"wkByteSec\":0,\"avgquSz\":0,\"r_await\":0,\"w_await\":0,\"await\":0,\"util\":0,\"util_wa\":0,\"load_read\":0,\"load_write\":0,\"load\":0,\"load_wa\":0},\"sda\":{\"tps\":0,\"rkByteSec\":0,\"wkByteSec\":0,\"avgquSz\":0,\"r_await\":0,\"w_await\":0,\"await\":0,\"util\":0,\"util_wa\":0,\"load_read\":0,\"load_write\":0,\"load\":0,\"load_wa\":0},\"sda1\":{\"tps\":0,\"rkByteSec\":0,\"wkByteSec\":0,\"avgquSz\":0,\"r_await\":0,\"w_await\":0,\"await\":0,\"util\":0,\"util_wa\":0,\"load_read\":0,\"load_write\":0,\"load\":0,\"load_wa\":0}}}}}}";
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(8080, function() {
console.log((new Date()) + ' 已经连接上8080');
});
wsServer = new WebSocketServer({
httpServer: server,
});
wsServer.on('request', function(request) {
//当前的连接
var connection = request.accept(null, request.origin);
// setInterval(function(){
//
// connection.sendUTF(json)
//
// },500)
console.log((new Date()) + '已经建立连接');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
//connection.sendUTF(str1);
connection.sendUTF(str1)
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + '断开连接');
});
});
最后记得main.js的钩子函数中,实例化websocket
const ws = this.$websocket ws.createSocket() 若要发送数据 ws.sendWSPush('数据')
var WebSocketServer = require('websocket').server;
var http = require('http');
var json = require('./myTest')
var str1 = "{\"action\": \"stat.nodes\", \"time\": 1590035916, \"data\": {\"nodes\": [{\"fd\": 19, \"ip\": \"192.168.10.11\", \"port\": 55296, \"allow\": true, \"down\": false, \"nodeName\": \"itv-auth-node-138121\", \"mainPort\": 8088, \"group\": \"hot\", \"targetUrl\": \"http://auth.liaowo.test\", \"version\": \"dev - 0\", \"runtime\": \"php: 7.3.18-1+ubuntu18.04.1+deb.sury.org+1, swoole: 4.5.1\", \"weights\": 0.0221}, {\"fd\": 233, \"ip\": \"角卷绵芽\", \"port\": 520, \"allow\": true, \"down\": false, \"nodeName\": \"咚咚咚\", \"mainPort\": 520, \"group\": \"hot\", \"targetUrl\": \"不是我的错吧\", \"version\": \"dev - 0\", \"runtime\": \"php: 7.3.18-1+ubuntu18.04.1+deb.sury.org+1, swoole: 4.5.1\", \"weights\": 0.0221}], \"dispatch_weights\": [{\"fd\": 19, \"weight\": 9997}], \"dispatch_count\": []}}";
var str2 = "{\"action\":\"stat.server\",\"time\":1590045218,\"data\":{\"info\":{\"name\":\"itv-auth-lb-138122\",\"version\":\"dev\",\"build_date\":\"0\",\"runtime_info\":\"php: 7.3.14-6+ubuntu16.04.1+deb.sury.org+1, swoole: 4.4.18\"},\"stat\":{\"server\":{\"start_time\":1590045183,\"connection_num\":2,\"accept_count\":3,\"close_count\":1,\"worker_num\":2,\"idle_worker_num\":1,\"tasking_num\":0,\"request_count\":31,\"worker_request_count\":1,\"worker_dispatch_count\":0,\"coroutine_num\":2},\"worker\":[{\"event_num\":8,\"signal_listener_num\":0,\"aio_task_num\":0,\"aio_worker_num\":2,\"c_stack_size\":2097152,\"coroutine_num\":2,\"coroutine_peak_num\":2,\"coroutine_last_cid\":191,\"pid\":5197,\"timer\":2,\"mem_usage\":3895688,\"mem_peak_usage\":3960464,\"stat_redis\":{\"consumer_num\":0,\"producer_num\":0,\"queue_num\":0,\"create\":0,\"max\":4,\"min\":0},\"http_pool\":null},{\"event_num\":6,\"signal_listener_num\":1,\"aio_task_num\":0,\"aio_worker_num\":2,\"c_stack_size\":2097152,\"coroutine_num\":4,\"coroutine_peak_num\":5,\"coroutine_last_cid\":166,\"pid\":5194,\"timer\":6,\"mem_usage\":3997240,\"mem_peak_usage\":4067208,\"stat_redis\":{\"consumer_num\":0,\"producer_num\":0,\"queue_num\":1,\"create\":1,\"max\":4,\"min\":0},\"http_pool\":null},{\"event_num\":8,\"signal_listener_num\":0,\"aio_task_num\":0,\"aio_worker_num\":2,\"c_stack_size\":2097152,\"coroutine_num\":4,\"coroutine_peak_num\":4,\"coroutine_last_cid\":292,\"pid\":5196,\"timer\":4,\"mem_usage\":5784680,\"mem_peak_usage\":6049248,\"stat_redis\":{\"consumer_num\":0,\"producer_num\":0,\"queue_num\":0,\"create\":0,\"max\":4,\"min\":0},\"http_pool\":null}],\"auth\":{\"accept\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"refuse\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"accept_m3u8\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"accept_ts\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"upstream_err\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"not_found\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"other_err\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"expired\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"invalid_sign\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"bad_ip\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"bad_self\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"bad_sess\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"bad_sign\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"secret_url\":{\"count\":0,\"qps\":0,\"qps_peak\":0},\"redis_err\":{\"count\":0,\"qps\":0,\"qps_peak\":0}},\"os\":{\"network\":{\"enp0s8\":{\"rx_bytes\":7479.24,\"tx_bytes\":19874.42,\"load_up\":0.03,\"load_down\":0.01,\"load\":0.02,\"load_wa\":0.02},\"enp0s3\":{\"rx_bytes\":0,\"tx_bytes\":0,\"load_up\":0,\"load_down\":0,\"load\":0,\"load_wa\":0},\"enp0s9\":{\"rx_bytes\":2414.68,\"tx_bytes\":182.16,\"load_up\":0,\"load_down\":0,\"load\":0,\"load_wa\":0}},\"disk\":{\"sdb\":{\"tps\":0,\"rkByteSec\":0,\"wkByteSec\":0,\"avgquSz\":0,\"r_await\":0,\"w_await\":0,\"await\":0,\"util\":0,\"util_wa\":0,\"load_read\":0,\"load_write\":0,\"load\":0,\"load_wa\":0},\"sda\":{\"tps\":0,\"rkByteSec\":0,\"wkByteSec\":0,\"avgquSz\":0,\"r_await\":0,\"w_await\":0,\"await\":0,\"util\":0,\"util_wa\":0,\"load_read\":0,\"load_write\":0,\"load\":0,\"load_wa\":0},\"sda1\":{\"tps\":0,\"rkByteSec\":0,\"wkByteSec\":0,\"avgquSz\":0,\"r_await\":0,\"w_await\":0,\"await\":0,\"util\":0,\"util_wa\":0,\"load_read\":0,\"load_write\":0,\"load\":0,\"load_wa\":0}}}}}}";
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(8080, function() {
console.log((new Date()) + ' 已经连接上8080');
});
wsServer = new WebSocketServer({
httpServer: server,
});
wsServer.on('request', function(request) {
//当前的连接
var connection = request.accept(null, request.origin);
// setInterval(function(){
//
// connection.sendUTF(json)
//
// },500)
console.log((new Date()) + '已经建立连接');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
//connection.sendUTF(str1);
connection.sendUTF(str1)
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + '断开连接');
});
});