【问题标题】:TCP to Server Database communicationTCP 到服务器数据库通信
【发布时间】:2015-06-06 13:19:23
【问题描述】:

我正在尝试了解客户端通过 TCP 连接向 node.js 服务器发送数据的正确通信方式。

客户端是一个小型电子设备,能够创建 TCP 套接字以与互联网通信。

远程服务器正在运行由 mongodb 数据库支持的 node.js。

什么是更好的沟通方式?

我没有太多经验,但我想到了一些想法:

  • 我可以向服务器发送 http POST,过滤消息并将内容重定向到数据库。
  • 在 http 服务器的不同端口上运行专用 TCP 服务器并直接连接到该服务器。

另一个问题是把安全放在哪里?客户端是否应该发送加密消息以在服务器端解码?

非常感谢

【问题讨论】:

    标签: node.js mongodb tcp server iot


    【解决方案1】:

    如果你想通过端口在服务器和客户端之间进行通信,你需要在服务器上创建 tcp 连接。

    在tcp连接中的通信方式与http请求不同。如果您的设备在端口上发送数据,它将在专用服务器上连同定义的端口一起接收。

    在 node.js 中用于 tcp 连接我们需要 'net' 模块

    var net = require("net");
    

    要创建服务器,将使用以下行

    var server = net.createServer({allowHalfOpen: true});
    

    我们需要编写以下代码来在专用端口上接收客户端请求。

    server.on('connection', function(stream) {
    
    });
    server.listen(6969);
    

    这里 6969 是端口。

    下面给出完整的sn-p来创建tcp连接的服务器。

    // server.js

    var net = require("net");
    global.mongo = require('mongoskin');
    var serverOptions = {
        'native_parser': true,
        'auto_reconnect': true,
        'poolSize': 5
    };
    var db = mongo.db("mongodb://127.0.0.1:27017/testdb", serverOptions);
    var PORT = '6969';
    var server = net.createServer({allowHalfOpen: true}); 
    // listen connection request from client side
    server.on('connection', function(stream) {
        console.log("New Client is connected on " + stream.remoteAddress + ":" + stream.remotePort);
        stream.setTimeout(000);
        stream.setEncoding("utf8");
        var data_stream = '';
    
        stream.addListener("error", function(err) {
            if (clients.indexOf(stream) !== -1) {
                clients.splice(clients.indexOf(stream), 1);
            }
            console.log(err);
        });
    
        stream.addListener("data", function(data) {
            var incomingStanza;
            var isCorrectJson = false;
            db.open(function(err, db) {
                if (err) {
                    AppFun.errorOutput(stream, 'Error in connecting database..');
                } else {
                    stream.name = stream.remoteAddress + ":" + stream.remotePort;
                    // Put this new client in the list
                    clients.push(stream);
                    console.log("CLIENTS LENGTH " + clients.length);
                    //handle json whether json is correct or not
                    try {
                        var incomingStanza = JSON.parse(data);
                        isCorrectJson = true;
                    } catch (e) {
                        isCorrectJson = false;
                    }
                // Now you can process here for each request of client
    
        });
        stream.addListener("end", function() {
            stream.name = stream.remoteAddress + ":" + stream.remotePort;
            if (clients.indexOf(stream) !== -1) {
                clients.splice(clients.indexOf(stream), 1);
            }
            console.log("end of listener");
            stream.end();
            stream.destroy();
        });
    
    });
    server.listen(PORT);
    
    console.log("Vent server listening on post number " + PORT);
    // on error this msg will be shown
    server.on('error', function(e) {
        if (e.code == 'EADDRINUSE') {
            console.log('Address in use, retrying...');
            server.listen(5555);
            setTimeout(function() {
                server.close();
                server.listen(PORT);
            }, 1000);
        }
        if (e.code == 'ECONNRESET') {
            console.log('Something Wrong. Connection is closed..');
            setTimeout(function() {
                server.close();
                server.listen(PORT);
            }, 1000);
        }
    });
    

    现在是时候为 tcp 服务器创建客户端了

    我们将通过 clint 发送所有请求以使连接获得可能的结果

    //client.js

    var net = require('net');
    var client = net.connect({
        //host:'localhost://', 
        port: 6969
    },
    function() { //'connect' listener
        console.log('client connected');
    
     var  jsonData = '{"cmd":"test_command"}';
    
        client.write(jsonData);
    });
    
    client.on('data', function(data) {
        console.log(data.toString());
    //    client.end();
    });
    
    client.on('end', function() {
        console.log('client disconnected');
    });
    

    现在我们在 tcp 通信中同时拥有服务器和客户端。

    要准备好监听服务器,我们需要在控制台中点击命令“node server.js”。

    之后服务器将准备好监听来自客户端的请求

    要从客户端进行调用,我们需要点击命令“node client.js”

    如果您可以根据您的实际要求进行修改,它将更有意义和有价值。

    谢谢

    【讨论】:

    • 感谢您对如何使用专用端口通信提供如此详细的答案。相信对有类似问题的人会有很大帮助!
    【解决方案2】:

    在安全方面,最好不要推出自己的解决方案,而是使用其他(聪明的)人已经验证过的软件。

    考虑到这一点,我将向服务器发送 HTTPS 请求。 Node.js 支持supports HTTPS。 HTTPS 为您提供了两件事:客户端可以验证服务器实际上是您的服务器,并且可以保护流量不被窃听。第三件事是验证客户不是坏人。这更难做到。您可以检查客户端的 IP 地址,或使用基于密码的身份验证。

    【讨论】:

    • 谢谢,我会尝试使用HTTPS。安全性不是一个大问题,但拥有某种安全性是件好事。
    猜你喜欢
    • 2013-07-01
    • 2011-08-03
    • 2016-05-16
    • 2020-04-15
    • 2021-12-29
    • 2014-10-24
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多