TLS to multiple clients and different messages

2019-08-22 21:05发布

I am planning a security system based on tcp. I want to secure it with TLS/SSL. I want to make a Client make a message to the server, the server has to check it and send to all the other clients a message back. I think it is unclear how to handle that, because the documentation of node.js tls only shows how you connect to the server and get a message back.

This is the code of the documentation:

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

const options = {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem'),

  rejectUnauthorized: true,
};

const server = tls.createServer(options, (socket) => {
  console.log('server connected',
              socket.authorized ? 'authorized' : 'unauthorized');
  socket.write('welcome!\n');
  socket.setEncoding('utf8');
  socket.pipe(socket);
});
server.listen(8000, () => {
  console.log('server bound');
});

Maybe you could make an example, because its totally unclear to me. Thanks for your help. If my question is unclear to you, please let me know.

1条回答
Lonely孤独者°
2楼-- · 2019-08-22 22:01
'use strict';
var tls = require('tls'); 
var fs = require('fs'); 
const PORT = 1337; 
const HOST = '127.0.0.1' 
var options = { 
key: fs.readFileSync('private-key.pem'), 
cert: fs.readFileSync('public-cert.pem') 
}; 
var users= [];
var server = tls.createServer(options, function(socket) { 

users.push(socket)



socket.on('data', function(data) { 
    for(var i = 0; i < users.length; i++){
    if(users[i]!=socket){
        users[i].write("I am the server sending you a message.");       
        }
}

console.log('Received: %s [it is %d bytes long]', 
data.toString().replace(/(\n)/gm,""), 
data.length); }); 


}); 

server.listen(PORT, HOST, function() { 
console.log("I'm listening at %s, on port %s", HOST, PORT); 
}); 

server.on('error', function(error) { 
console.error(error); 

server.destroy(); 
});
查看更多
登录 后发表回答