app.js
var wsWorkStation = require('./lib/wsWorkStation');
wsWorkStation.initWorkStations();
lib/wsWorkStation
const WebSocket = require('ws');
const log4js = require('../log-config');
const logger = log4js.getLogger('wsclient');
const db = require('./mysqldb');
const WorkStationSql = require('../models/workstation');
const wsWorkStations = [];
exports.initWorkStations = function () {
db.query(WorkStationSql.listeWorkStations, [], function (err, rows) {
if (err) {
logger.error("Database operation error! error:" + err);
} else if (rows.length > 0) {
logger.info("Work Stations connection state is being initialized! ");
var stationArr = rows;
var actions = [];
var updateOnlineStatus = function (port, ipAddress, callback) {
new Promise((resolve, reject) => {
var wsClient = exports.newWorkStation(ipAddress, port);
resolve(wsClient);
}).then((wsClient) => {
if (wsClient.readyState == 1) {
db.query(WorkStationSql.updateOnlineStatusByIp,[1,ipAddress],function(err,rows){
if(err){
logger.info(err);
}else{
logger.info("The IP with the successful workstation connection is " + ipAddress);
return callback(0);
}
})
} else {
db.query(WorkStationSql.updateOnlineStatusByIp,[0,ipAddress],function(err,rows){
if(err){
logger.info(err);
}else{
logger.error("The IP with the failed workstation connection is " + ipAddress);
return callback(1);
}
})
}
})
for (var i = 0; i < stationArr.length; i++) {
var action = () => { // 将每一次循环方法定义为一个方法变量
return new Promise((resolve, reject) => { // 每个方法返回一个Promis
((index) => {
updateOnlineStattus(stationArr[index].port, stationArr[index].ipAddress, function (err, retTtem) {
resolve();
});
})(i)
})
}
actions.push(action()); // 将每次循环调用的方法添加到方法数组中
Promise.all(actions).then(() => { // 调用Promise的all方法,传入方法数组,
logger.info("All workstations initiate websocket connection")
})
} else {
logger.info("There is no workstation, please create a workstation! ");
}
})
}
exports.newWorkStation = function (ipaddress, port) {
return new Promise((resolve, reject) => {
var createdWsClient = wsWorkStations.filter(item => item.ipaddress == ipaddress);
if (createdWsClient.length == 0) {
if(!ipaddress){
logger.error("The ipaddress is empty!")
}
if(!port){
logger.error("The port is empty!")
}
var wsClient = new WebSocket('ws://' + ipaddress + ':' + port);
if (wsClient) {
wsClient.on('open', function open() {
wsClient.ipaddress = ipaddress;
wsClient.port = port;
wsWorkStations.push(wsClient);
resolve(wsClient);
});
wsClient.on('message', function (message) {
});
wsClient.on("error", (error) => {
resolve(wsClient);
});
wsClient.on("close", () => {
resolve(wsClient);
});
}
} else {
resolve(createdWsClient[0]);
}
})
}