Nodejs为客户端生成远程tail和socket-io

时间:2017-09-14 12:58:54

标签: node.js socket.io child-process tail

我是Nodejs的新手,我正在构建一个ssh到远程计算机并获得tail -f日志文件的应用程序。

我收到的通过socket-io(版本2.0.3)发送给客户的日志文件的行

现在我遇到一个问题,当第二个浏览器尝试tail不同的日志时,新日志会发送到两个浏览器而不是只发出请求的人。 我不确定我的socket-io代码或child_process是否存在问题。

这是服务器:

const express = require('express'),
    app = express(),
    path = require('path'),
    bodyParser = require('body-parser'),
    logger = require('morgan'),
    server = require('http').Server(app),
    io = require('socket.io')(server),
    spawn = require('child_process').spawn,
    events = require('events'),
    eventEmitter = new events.EventEmitter();


// Fix body of requests
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

// Log the requests
app.use(logger('dev'));

// Serve static files
app.use(express.static(path.join(__dirname, '.')));

// Add a basic route – index page
app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname, 'index.html'));
});

io.on('connection', (socket) => {
    console.log(`client connected ${socket.client.id}`);
    eventEmitter.on('tail', (data) => {
        socket.tail = spawn('ssh', ['root@' + 'quality-p.company.com', 'tail -f', data.service], { shell: true });
        socket.tail.stdout.on('data', (data) => {
            console.log(`got new data ${data.toString()}`);
            socket.emit('newLine', {line: data.toString().replace(/\n/g, '<br />')});
        });
    });
});

app.get('/tail', (req, res) => {
    eventEmitter.emit('tail', req.query);
    res.sendStatus(200);
});

// Bind to a port
server.listen(3005, () => {
    console.log('running on localhost:' + 3005);
});

客户端:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="./node_modules/socket.io-client/dist/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script>
        $(() => {
            let socket = io();
            socket.on('connect', () => {
                console.log('connected');
            });
            socket.on('newLine', (data) => {
                console.log(`new data: ${data.line}`);
                $("#tailing").append(data.line);
            });
            $('#tail').click(() => {
                $.get('/tail', {
                    service: $('#service').val()
                });
            });
        });
    </script>
    <title>Title</title>
</head>
<body>
<select id="service">
    <option id="tnet" value="/var/log/tnet">tnet</option>
    <option id="consul" value="/var/log/consul">consul</option>
</select>
<button id="tail">tail</button>
<div id="tailing" style="background-color: antiquewhite;">
</div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

服务器

const express = require('express'),
    app = express(),
    path = require('path'),
    bodyParser = require('body-parser'),
    logger = require('morgan'),
    server = require('http').Server(app),
    io = require('socket.io')(server),
    spawn = require('child_process').spawn;


// Fix body of requests
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

// Log the requests
app.use(logger('dev'));

// Serve static files
app.use(express.static(path.join(__dirname, '.')));

// Add a basic route – index page
app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname, 'index.html'));
});

var tails = {};

io.on('connection', (socket) => {
    console.log(`client connected ${socket.client.id}`);
    socket.on('tail', (data) => {
        socket.join(data.service);
        if (typeof tails[data.service] == "undefined") {
            tails[data.service] = spawn('ssh', ['root@' + 'quality-p.company.com', 'tail -f', data.service], {
                shell: true
            });
            tails[data.service].stdout.on('data', (data) => {
                console.log(`got new data ${data.toString()}`);
                io.to(data.service).emit('newLine', {
                    line: data.toString().replace(/\n/g, '<br />')
                });
            });
        }
    });
});


// Bind to a port
server.listen(3005, () => {
    console.log('running on localhost:' + 3005);
});

客户端

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <script src="./node_modules/socket.io-client/dist/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script>
        $(() => {
            let socket = io();
            socket.on('connect', () => {
                console.log('connected');
            });
            socket.on('newLine', (data) => {
                console.log(`new data: ${data.line}`);
                $("#tailing").append(data.line);
            });
            $('#tail').click(() => {
                socket.emit('tail', {
                    service: $('#service').val()
                });
            });
        });
    </script>
    <title>Title</title>
</head>

<body>
    <select id="service">
    <option id="tnet" value="/var/log/tnet">tnet</option>
    <option id="consul" value="/var/log/consul">consul</option>
</select>
    <button id="tail">tail</button>
    <div id="tailing" style="background-color: antiquewhite;">
    </div>
</body>

</html>