net模块有一个createServer函数,允许您创建网络包装器。这在Nodejs的本地运行时可以正常工作,但在Bluemix中运行时无法确定主机地址。服务器似乎已创建,但经过进一步检查,我发现server.address为空白。
var tls = require('tls');
var fs = require('fs');
var net = require('net');
var tunnelHost = (process.env.VCAP_APP_HOST || 'localhost');
var tunnelPort = 8888;
var server;
var gatewayOptions = {
host: 'http://cap-sg-prd-5.integration.ibmcloud.com/',
port: '15133',
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem'),
ca: fs.readFileSync('ca.pem')
};
console.log("starting createSecureTunnel");
//create a server end point to use as a network wrapper for the secure gateway
server = net.createServer(function (connListener){
console.log('net server created');
connListener.on('end', function() {
console.log('client disconnected');
});
connListener.on('uncaughtException', function(err){
console.log('exception caught: ' + JSON.stringify(err));
});
//connect to farside, local/private server
connectFarside(connListener, function(err, remoteSocket){
if (err){
console.log(err);
}
console.log('connection made');
remoteSocket.pipe(connListener);
console.log('remote socket connecte to local connListener');
connListener.pipe(remoteSocket);
console.log('local connListener connected to remote socket');
});
});
//setup listener for network wrapper
server.listen(tunnelPort, tunnelHost, function(){
console.log('tunnel created at: ' + tunnelHost +":"+ tunnelPort); //.address +":"+ server.address().port);
});
//createa a TLS connection to the secure gateway
function connectFarside(conn, callback) {
console.log("starting connectFarside");
try {
console.log("initiating farside connection");
var socket = tls.connect(gatewayOptions, function(){
console.log("tunnel connected to " + gatewayOptions.host +":"+ gatewayOptions.port);
callback(null, socket);
});
socket.on("error", function(err){
console.log("Socket error: " + JSON.stringify(err));
});
} catch(err) {
console.log(err);
callback(err);
}
}
答案 0 :(得分:2)
Bluemix为您的应用程序提供了一个可以运行的端口,这就是它在Bluemix中不起作用的原因。您开始使用以下代码行在端口8888
上启动您的应用。
var tunnelPort = 8888;
应该改为
var tunnelPort = process.env.VCAP_APP_PORT || 8888;
上面一行将读取一个名为VCAP_PORT
的环境变量,其中Bluemix为您的应用分配端口,如果它未运行Bluemix,它将在端口8888
上运行。
您的应用可通过端口80
和443
通过网络访问。 Bluemix将为您的应用程序加载余额。