TCP 到服务器数据库通信

TCP to Server Database communication

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

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

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

什么是更好的沟通方式?

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

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

非常感谢

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

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

如果你想通过端口在服务器和客户端之间进行通信,你需要在服务器上创建 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是端口

下面给出了创建 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'

如果能根据自己的实际需要进行修改,会更有意义,更有价值。

谢谢