0

我目前正在 Node-js 中开发一个应用程序来通过 ssh2 启动进程。所以我使用两个库。第一个是ssh2,第二个是ssh2-promise。问题是如何向我的进程发送中止信号。我不明白我怎么能用这两个图书馆做到这一点。我可以关闭套接字,但应用程序将继续,我没有得到 PID。

所以我尝试下面的代码。它启动了我的进程,但我无法阻止它。

async function sendCommand(commandString) {
    let socket = await sshPromise.spawn(commandString);
    process.push(socket);
    socket.on('data', function (data) {
       console.log(data);
    });
    console.log('Socket push in process array', process);
    await sleep(2000);
   stopFunctionSocket();
}

function stopFunctionSocket() {
     process.forEach( function(socket) {
        socket.on('exit', function () {
            console.log('Process killed');
        });
    });
}

sendCommand('sipp/sipp -sn uas 127.0.0.1').then(
     result => {
         console.log(result);
     }
);

我有我的输出,但现在,我怎么能中止这个过程?

非常感谢。

4

2 回答 2

0

我们可以这样做,

function getWithCancel(url, token) { // the token is for cancellation
   var xhr = new XMLHttpRequest;
   xhr.open("GET", url);
   return new Promise(function(resolve, reject) {
      xhr.onload = function() { resolve(xhr.responseText); });
      token.cancel = function() {  // SPECIFY CANCELLATION
          xhr.abort(); // abort request
          reject(new Error("Cancelled")); // reject the promise
      };
      xhr.onerror = reject;
   });
};

这会让你做:

var token = {};
var promise = getWithCancel("/someUrl", token);

// later we want to abort the promise:
token.cancel();

解释 您有几种选择:

  • 使用像bluebird这样的第三方库,它的移动速度比规范快得多,因此可以取消以及许多其他好东西——这就是像 WhatsApp 这样的大公司所做的
  • 传递取消令牌。
  • 使用第三方库非常明显。至于令牌,您可以让您的方法接受一个函数,然后调用它,如下所示:

    于 2019-09-12T08:06:49.423 回答
    0

    尝试使用这个:

    socket.kill()
    

    https://github.com/sanketbajoria/ssh2-promise/blob/bd573d2849a78ebd8315512449f4bd588df3b598/src/sshConnection.ts#L127

    于 2019-09-12T12:39:57.110 回答