Node.js无法通过网络建立连接

时间:2012-01-31 01:12:25

标签: node.js network-programming

我遇到Node.js的问题。我写了一个非常简单的TCP服务器,它接收JSON并在MySQL DB上执行简单的数据库操作。一切都在当地正常运作。我正在使用nc <server ip address> <port>使用netcat对其进行测试。

当我在本地执行此操作时,我可以访问服务器,但是当我尝试通过网络执行此操作时,它无法连接。 Netcat在网络上正常工作,这让我很困惑。我也尝试使用HTTP服务器示例,但我也无法使用它。我正在使用Mac OS X Snow Leoppard和Arch Linux。我无法连接/连接其中任何一个。有任何想法吗?我是否必须做一些特别的事情让Node.js连接?

如果有人有任何想法,我会非常高兴=)我没有粘贴源代码,因为它长达121行,但如果有人需要它,我会把它交给它。

1 个答案:

答案 0 :(得分:0)

从OP的问题中提取的解决方案

我搞砸了很多时间。我就像在示例中一样使用server.listen(port, '127.0.0.1'),这意味着只有localhost可以访问该服务。

这是我的源代码:

//+-----------------------------------------+
//| TCP Server                  |
//| Description: MySQL connector.       |
//|    Speaks JSON over TCP         |
//+-----------------------------------------+
//| Author: /usr/share              |
//+-----------------------------------------+
//| Dependencies: Node.js, MySQL,       |
//|   MySQL for Node.js             |
//+-----------------------------------------+

/********************************************
 * Standard functions               *
 ********************************************/

/*
 * Deletes trailing spaces
 */
function trim(str) {
    return str.replace(/^\s*/, "").replace(/\s*$/, "");
}

/*
 * Writes the log with the operations executed in order
 */
function writeLog(str) {
    var fs = require('fs');
    var log = fs.createWriteStream('log.txt', {'flags': 'a'});
    log.write(str);
}

/*
 * Executes DML instructions on the MySQL DB
 * op parameters:
 * [0] Select
 * [1] Insert
 * [2] Update
 * [3] Delete
 */
function queryDB(request, socket) {
    var Client = require('mysql').Client;
    var client = new Client();
    client.user = 'root';
    client.password = '';
    client.host='127.0.0.1';
    client.port='3306';
    client.database='usrshare';

    var op = request['op'];
    var query;

    // Parse a query from its corresponding op
    if(op == 0) {
    query = 'SELECT * FROM DATA';
    } else if(op == 1) {
    query = "INSERT INTO `usrshare`.`data` (`str`) VALUES ('" + request['data'] + "');";
    } else if(op == 2) {
    query = "DELETE FROM `usrshare`.`data` WHERE `id` = " + request['id'];
    } else if(op == 3) {
    query = "UPDATE `usrshare`.`data` SET `str` = '" + request['data'] + "' where `id` = " + request['id']; 
    }else {
    console.log("This shouldn't be happening");
    return null;
    }

    // Query the current database
    client.query(
    query,
    function selectData(err, results, fields) {
        if (err) {
        console.log("Error: " + err.message + "\n");
        socket.write("Error: " + err.message + "\n");
        writeLog("Error: " + err.message + "\n");
        return null;
        }
        client.end();

        if(op == 0) {
        socket.write(JSON.stringify(results) + "\n");
        writeLog("op:" + op + "\n");
        } else if(op == 1) {
        socket.write("Row inserted\n");
        writeLog("op:" + op + " data: " + request['data'] + "\n");
        } else if(op == 2) {
        socket.write("Row deleted\n");
        writeLog("op:" + op + " id: " + request['id'] + "\n");
        } else if(op == 3) {
        writeLog("op:" + op + " id: " + request['id'] + " data: " + request['data'] + "\n");
        socket.write("Row updated\n");
        }

        return results;
    });
}

//-------------------------------------------
//-------------------------------------------

/********************************************
 * Entry point                  *
 ********************************************/
if(process.argv.length != 3) {
    console.log('Error, use: ' + process.argv[0] + ' ' + process.argv[1] + ' <port>');
    process.exit(1);
}

var port = process.argv[2];
var net = require('net');

// Actual server
var server = net.createServer(function (socket) {
    socket.setEncoding('utf8');
    socket.on('data', function(data) {
    request = JSON.parse(data);
    queryDB(request, socket);
    });
});

// Listening on localhost
server.listen(port, '127.0.0.1');
console.log('Listening on port ' + port);