const fs = require('fs');
const http = require('http');
const webSocketsServerPort = 8888;
var wsServer = require('ws').Server;

const processRequest = (req, res) => {
    res.writeHead(200);
    res.end('WebSocket Test');
}

const app = http.createServer(processRequest).listen(webSocketsServerPort, () => {
    console.log(`Server has been started, listening:${webSocketsServerPort}......`);
});

const wss = new wsServer({
    server: app,
    autoAcceptConnections: false
})

var clients = [];

wss.on('request', (request) => {
    console.log(getNow() + '' + request.origin + '请求连接');
    var wsConnect = request.accept(null, request.origin);
    clients.push(wsConnect);
    wsConnect.clientIdx = clients.length - 1;
    console.log(getNow() + '' + request.origin + '已建立连接...');
});

wss.on('connection', (wsConnect) => {
    console.log(`Client Connected`);
    wsConnect.on('message', (message) => {
        console.log(`Server recv : ${message}`);
        wsConnect.send(`Hello WebSocket From Server`, (err) => {
            if (err) {
                console.error('Server Error');
            }
        })
    });
});

wss.on('close', function(wsConnect) {
    console.log(getNow() + "****" + wsConnect.remoteAddress + " 断开链接...");
    clients.splice(wsConnect.clientIdx, 1);
});
