我也遇到过类似的情况。我通过在http.request()(Node.js HTTP 客户端)的选项参数中返回ssh2 创建的stream 来使用现有套接字。一些示例代码:
var http = require('http');
var Client = require('ssh2').Client;
var conn = new Client();
conn.on('ready', function () {
// The connection is forwarded to '0.0.0.0' locally.
// Port '0' allows the OS to choose a free TCP port (avoids race conditions)
conn.forwardOut('0.0.0.0', 0, '127.0.0.1', 80, function (err, stream) {
if (err) throw err;
// End connection on stream close
stream.on('close', function() {
conn.end();
}).end();
// Setup HTTP request parameters
requestParams = {
host: '127.0.0.1',
method: 'GET',
path: '/',
createConnecion: function() {
return stream; // This is where the stream from ssh2 is passed to http.request()
}
};
var request = http.request(requestParams, function(response) {
response.on('data', function (chunk) {
// Do whatever you need to do with 'chunk' (the response body)
// Note, this may be called more than once if the response data is long
})
});
// Send request
request.end();
});
}).connect({
host: '127.0.0.1',
username: 'user',
password: 'password'
});
我遇到了一个未定义 socket.destroySoon() 的问题,作为一种解决方法,它可以在返回 stream 之前定义。它只是调用socket.destroy()。示例:
createConnection: function () {
stream.destroySoon = function () {
return stream.destroy();
}
return stream;
}
注意:我没有对示例进行全面测试,因此使用风险自负。