将 Node.js TCP 服务器从本地主机移动到 VPS (Openshift)

Move Node.js TCP server from localhost to VPS (Openshift)

我有一个工作的 node.js 服务器,当它 运行 在本地主机上时,我可以从我的客户端发送和接收数据(写在 java 中)。但是,当我将 server.js 移动到 Openshift(免费)的 VPS 应用程序时,客户端无法再连接到 server.js.

我已按照说明上传文件,我通过终端打开 SSH 连接到服务器,导航到 repo 文件夹(上传文件所在的位置),运行 "node server.js"(看起来在线,没有错误,on.('online',..) 事件激活。

然后当我 运行 我计算机上的客户端无法连接到 server.js。

server.js:

var os      = require('os');
var HOST    = process.env.OPENSHIFT_NODEJS_IP;;
var PORT    = process.env.PORT || 80;
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;
var net     = require('net');

console.log("Hostname: " + HOST + "\nPort: " + PORT);

if (cluster.isMaster) {
    cluster.SCHED_RR;


    for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    Object.keys(cluster.workers).forEach(function(id){
        console.log("I am runnong with ID: " + cluster.workers[id].process.pid);
    });

    console.log('\n');

    cluster.on('online', function(worker) {
        console.log('Worker: ' + worker.process.pid + " listning on port " + PORT);
    });

    cluster.on('exit', function(worker, code, signal){
        console.log("Worker " + worker.process.pid + " died")
    });

} else {

    // Load the TCP Library
    net = require('net');

    // Keep track of the chat clients
    var clients = [];

    // Start a TCP Server
    var server = net.createServer(function (socket) {

        console.log('\n'); 
        // Identify this client
        socket.name = socket.remoteAddress + ":" + socket.remotePort 

        // Put this new client in the list
        clients.push(socket);

        // Send a nice welcome message and announce
        socket.write("Welcome " + socket.name + "\n\n");
        broadcast(socket.name + " joined the chat\n", socket);

        // Handle incoming messages from clients.
        socket.on('data', function (data) {
            //var ls = net.connect(5001, 'localhost');

            var string = data + "";

            //console.log(string);
            var message = string.split("|");

            broadcast("    Passing data from "+message[2]+" to "+message[1] + "\n    " + message[3], socket);


            //ls.write(string);
            //ls.end();

        });

        socket.on('connect', function(){
          broadcast("\n    New connection opened.\n");
        });

        // Remove the client from the list when it leaves
        socket.on('end', function () {
            clients.splice(clients.indexOf(socket), 1);
            broadcast("\n" + socket.name + " left the chat.\n");
        });

        // Send a message to all clients
        function broadcast(message, sender) {
            clients.forEach(function (client) {
                // Don't want to send it to sender
                if (client === sender) return;
                client.write(message);
            });
            // Log it to the server output too
            process.stdout.write(message)
        }

    })

    server.listen(PORT, HOST);

    server.on('error', function (e) {
        if (e.code == 'EADDRINUSE') {
            console.log('Address in use, retrying...');
            setTimeout(function () {
                server.close();
                server.listen(PORT, HOST);
            }, 1000);
        }
        else if (e.code == 'ECONNREFUSED') {
            console.log('Connection refused');
        }
    });

}

Client.java(相关部分)

public static void main(String args[]) {
    String s = getPackage();

    try {
        System.out.print("\n");

        /*InetAddress addr;
        Socket sock = new Socket("ex-std-node272.prod.rhcloud.com", 80);
        addr = sock.getInetAddress();
        System.out.println("Connected to " + addr);*/


        Socket skt = new Socket("127.10.100.1", 80);
        BufferedReader inStream = new BufferedReader(new
        InputStreamReader(skt.getInputStream()));

        DataOutputStream outStream = new DataOutputStream(skt.getOutputStream());

        //System.out.print("   Received string: '");

        //while (!inStream.ready()) {}
        //System.out.print(inStream.readLine()); // Read one line and output it

        System.out.print("'\n\n");

        // Send first message
        //outStream.writeByte(1);
        outStream.writeUTF(s);
        //outStream.flush(); // Send off the data
        //outStream.write(b,0,b.length);
        outStream.flush(); // Send off the data


    }
    catch(Exception e) {
        System.out.print("    Error: " + e);
    }

}

当我 运行 server.js(在 VPS)时,它会给我主机名:127.10.100.1 和端口:80,然后我将其粘贴到客户端中。

那么,我需要如何处理才能连接的代码?

您需要侦听端口 8080,而不是端口 80。请尝试阅读开发人员中心关于端口绑定的这一部分:https://developers.openshift.com/en/managing-port-binding-routing.html

首先要注意的是,server.js 中的 PORT 应该等于 process.env.OPENSHIFT_NODEJS_PORT8080,正如 Corey 已经提到的那样。

第二个问题是,当您 运行 您的客户端在您的本地计算机上时,您应该连接到 URL 的主机,该主机在您创建应用程序时提供给它 [=13] =].您可以在发出命令时看到您的应用程序 url:

rhc show-app <appname>