среда, 4 марта 2020 г.

Node.js Net TCP server and TLS (SSL) server

Node.js Net TCP server and client.


Файл tcp-socket-server.js

var net = require('net');

var server = net.createServer();

server.maxConnections = 10;

server.on('connection', function (clientSocket) {
   
    var clientRequest, serverResponse;
    clientRequest = serverResponse = clientSocket;
   
    console.log('Client connected.');

    console.log('Server local address: ' + clientSocket.localAddress + ':' + clientSocket.localPort + '. Client remote address: ' + clientSocket.remoteAddress + ':' + clientSocket.remotePort + '.');

    server.getConnections(function (error, count) {
        if (error) {throw error;}
        console.log('Number of clients connected to server: ' + count);
    });
   
    clientRequest.setEncoding('utf8');
   
    clientRequest.setTimeout(1000);
    clientRequest.on('timeout', function () {
        console.log('Client request timeout.');
        clientRequest.end(); // или также можно выполнить clientRequest.destroy(); для закрытия соединения с клиентом.
        console.log('Connection with client ' + clientSocket.remoteAddress + ':' + clientSocket.remotePort + ' closed.');
        server.close();
    });
   
    clientRequest.on('data', function (data) {
       console.log('Received data from client: "' + data + '". Data size: ' + clientRequest.bytesRead);
       serverResponse.write('Data from server.');
       console.log('Sent data to client size: ' + serverResponse.bytesWritten);
    });
   
    clientRequest.on('end', function () {
        console.log('Client ' + clientSocket.remoteAddress + ':' + clientSocket.remotePort + ' disconnected from server.');
        server.getConnections(function (error, count) {
            if (error) {throw error;}
            console.log('Number of clients connected to server: ' + count);
        });
    });
   
});

server.on('close', function () {
    console.log('Server closed.');
});

server.on('error', function (error) {
    throw error;
});

server.on('listening', function () {
    if (server.listening) {
        console.log('Server started at ' + server.address().address + ':' + server.address().port + '. Family: ' + server.address().family + '.');
    }
});

server.listen(8080, '127.0.0.1');


Файл tcp-socket-client.js

var net = require('net');

var client = net.connect(8080, '127.0.0.1', function () {
    console.log('Client local address: ' + client.localAddress + ':' + client.localPort + '. Remote server address: ' + client.remoteAddress + ':' + client.remotePort + '.');
});

console.log('Is client pending? ' + client.pending);
console.log('Is client connecting? ' + client.connecting);

client.setNoDelay(true); // Set no delay before write to server. No buffer data.

client.setEncoding('utf8');

client.setTimeout(500);
client.on('timeout', function () {
    console.log('Client connection timeout.');
    console.log('Connection with server closed.');
});

client.on('lookup', function (error, address, family, host) { // DNS lookup - работает при подключении к сайтам типа google.com:80
    if (error) {throw error;}
    console.log('Found server with IP-address: ' + address + '. Family: ' + family + '.');
});

client.on('connect', function () {
    console.log('Is client pending? ' + client.pending);
    console.log('Is client connecting? ' + client.connecting);
    console.log('Client connected to server.');
   
    client.write('Second data from client.');

    console.log('Sent second data to server - data size: ' + client.bytesWritten);
    console.log('Data in client buffer size: ' + client.bufferSize);
});

client.on('ready', function () {
    console.log('Client ready to transfer data.');
});

client.on('data', function (data) {
    console.log('Receive data from server: "' + data + '". Data size: ' + client.bytesRead);
});

client.on('end', function () {
    console.log('Client disconnected from server.');
});

client.on('error', function (error) {
    throw error;
});

client.write('First data from client.');

console.log('Sent first data to server - data size: ' + client.bytesWritten);
console.log('Data in client buffer size: ' + client.bufferSize);


Node.js TLS (SSL) server and client.


Выполнить установку библиотеки "selfsigned":

npm install selfsigned


Файл create-ssl-certificates.js

// npm install selfsigned

var fs = require('fs');
var selfsigned = require('selfsigned');
var attrs = [{name: 'commonName', value: 'contoso.com'}];
var pems = selfsigned.generate(attrs, {days: 365});

console.log(pems);

fs.writeFile('./private-key.pem', pems.private, function (error) {if (error) {throw error;}});
fs.writeFile('./public-key.pem', pems.public, function (error) {if (error) {throw error;}});
fs.writeFile('./cert.pem', pems.cert, function (error) {if (error) {throw error;}});


Файл private-key.pem

-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCRyF/m2lVb7BVpudPydqz8WUOItxP6GI7XtHVdPJCWa2Ktjj1R
6W2HZm3eqNV7j4IgSStRfZlPDNhT9P3BC7bbyyaODxDlu6hyM24NHm22H6q5QDsC
web/p8q5GAR2978X/Uys2iJGZmOn2RCE5VJhRFcykdN2BohSPdzh7GUh+wIDAQAB
AoGAf/FYYXWqxnLq1BA3+Cq5ZPs+bwUmLi9RZfRFsJ9P0gPK5cDZBkOUUenOcUTB
n6ByNr2gm/NcEmmWjhCMh9ktEGQhnw3VX3UuQP/NXN+ZIDpySA6wQVxZS3b3eIL0
a7rb6W9QH8/Ww1ggLnGdgE6MBRAh5dc1xHoK6TtcOPkKziECQQDBfVO5rFJLwqPR
L1FRyou2SpOoZvqT3RPs+vv2VLdmDPFv56zGKG8xTZky2nOuK345P6tcr5cp5PXo
Nz37L6BLAkEAwOFsb1JZLorliE1/n7psE7iTAjc5OuT1D+Bmkuhh524PYC4jcvxg
d8aFteskUFjE9rhy9Khnt7rZ4PKtxwZXEQJBAJU0+h2SXxwBCqbDYGg8UyTNubQB
RXZE45q5qRc6GPtfO8fZ1ggxIh3ZAyyN/OrwqzOmf5TH6z/pSiA6iVdsUKUCQCiS
AfX0c0/H5XnjGzokw0DurPVlWkNaD3X0dH7oJFfCnbdUXR59mWj4N/3I5Q2FboCa
0YtGtPI/ej7HrOfVHJECQETRNoUKDf6lqsMc3pK1vTNjF80IU9wfYjTuIHBYRVWo
vBHiGtBm5yx6SqrQ/rSpfTNNmO94A1Hl4AoLSFnrk+c=
-----END RSA PRIVATE KEY-----


Файл public-key.pem

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCRyF/m2lVb7BVpudPydqz8WUOI
txP6GI7XtHVdPJCWa2Ktjj1R6W2HZm3eqNV7j4IgSStRfZlPDNhT9P3BC7bbyyaO
DxDlu6hyM24NHm22H6q5QDsCweb/p8q5GAR2978X/Uys2iJGZmOn2RCE5VJhRFcy
kdN2BohSPdzh7GUh+wIDAQAB
-----END PUBLIC KEY-----


Файл cert.pem

-----BEGIN CERTIFICATE-----
MIIB7zCCAVigAwIBAgIJIqEQUie5+FU5MA0GCSqGSIb3DQEBBQUAMBYxFDASBgNV
BAMTC2NvbnRvc28uY29tMB4XDTE5MDcxMjE1MTcxMVoXDTIwMDcxMTE1MTcxMVow
FjEUMBIGA1UEAxMLY29udG9zby5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJ
AoGBAJHIX+baVVvsFWm50/J2rPxZQ4i3E/oYjte0dV08kJZrYq2OPVHpbYdmbd6o
1XuPgiBJK1F9mU8M2FP0/cELttvLJo4PEOW7qHIzbg0ebbYfqrlAOwLB5v+nyrkY
BHb3vxf9TKzaIkZmY6fZEITlUmFEVzKR03YGiFI93OHsZSH7AgMBAAGjRTBDMAwG
A1UdEwQFMAMBAf8wCwYDVR0PBAQDAgL0MCYGA1UdEQQfMB2GG2h0dHA6Ly9leGFt
cGxlLm9yZy93ZWJpZCNtZTANBgkqhkiG9w0BAQUFAAOBgQBMXBY8LmuZ1DCgzsg2
l4fcHJ8lDUgc/17PF7TWCZLiIuH8To7Gg1x9yli2M9w8vMXrbbhZeluokR8gzeol
pJoZTlP+JZ+lYl+5q01f/zea+7lZW3WksMfsfau6ajZMn8O9L8rv3M6sSD0Dei/1
hAZZMrupHYINWnVgjShzVGpFBA==
-----END CERTIFICATE-----


Файл tls-socket-server.js

var tls = require('tls');
var fs = require('fs');

var options = {
    key: fs.readFileSync('./private-key.pem'),
    cert: fs.readFileSync('./public-key.pem'),
    ca: [fs.readFileSync('./cert.pem')],
    requestCert: true,
    rejectUnauthorized: true
};

const server = tls.createServer(options, function (clientSocket) {
});

server.on('connection', function (clientSocket) {
    console.log('insecure connection');
    console.log('Server connected ' + (clientSocket.authorized ? 'authorized' : 'unauthorized'));
    clientSocket.setEncoding('utf8');
    clientSocket.on('data', function (data) {
        console.log(data);
        clientSocket.write('Welcome.');
    });
    clientSocket.on('end', function () {
        console.log('End');
    });
});

server.on('secureConnection', function (clientSocket) {
    // clientSocket.authorized will be true if the client cert presented validates with our CA
    console.log('secure connection; client authorized: ', connection.authorized);
    console.log('Server connected ' + (clientSocket.authorized ? 'authorized' : 'unauthorized'));
    clientSocket.setEncoding('utf8');
    clientSocket.on('data', function (data) {
        console.log(data);
        clientSocket.write('Welcome.');
    });
    clientSocket.on('end', function () {
        console.log('End');
    });
});

server.on('error', function (error) {
    throw error;
});

server.listen(443, '127.0.0.1', function () {
    console.log('Server started at 127.0.0.1:443');
});


Файл tls-socket-client.js

var tls = require('tls');
var fs = require('fs');

var options = {
    ca: [fs.readFileSync('./server-cert.pem')]
};

var client = tls.connect(443, '127.0.0.1', options, function () {
    console.log('Client connected ' + (client.authorized ? 'authorized' : 'unauthorized'));
    if (client.authorized) {
        console.log('Connection authorized by a Certificate Authority.');
    } else {
        console.log('Connection not authorized: ' + client.authorizationError)
    }
    client.write('I am the client sending you a message.');
});

client.setEncoding('utf8');

client.on('data', function (data) {
    console.log(data);
});

client.on('end', function () {
    console.log('Ended')
});

client.on('close', function () {
    console.log('Connection closed');
});

client.on('error', function(error) {
    throw error;
});

Комментариев нет:

Отправить комментарий