首页 文章

TCP到服务器数据库通信

提问于
浏览
0

我正在尝试理解客户端通过TCP连接向node.js服务器发送数据之间进行通信的正确方法 .

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

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

什么是更好的沟通方式?

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

  • 我可以将http POST发送到服务器,过滤消息并将内容重定向到数据库 .

  • 在另一个端口上的http服务器中运行专用TCP服务器,并直接连接到此服务器 .

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

非常感谢你

2 回答

  • 0

    在安全性方面,最好不要推出自己的解决方案,而应使用其他(智能)人员验证过的软件 .

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

  • 1

    如果要在端口上的服务器和客户端之间进行通信,则需要在服务器上创建tcp连接 .

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

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

    var net = require("net");
    

    要使用创建服务器跟随行

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

    我们需要编写以下行来接收专用端口上的客户端请求 .

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

    这里6969是港口 .

    下面给出完整的片段来创建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'

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

    谢谢

相关问题