Friday 19 May 2017

nodejs tls module for server-client communication without browser

I wish to securely send messages back and forth between a client and a remote server (just an IP address and a port) using nodejs. The client runs a local .js file and does not use a browser. I have tried to do so using the node TLS module (https://nodejs.org/api/tls.html).

The handshake works perfectly fine, but I can not manage to send a message from the server to the client. My current code is:

client.js

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

const options = {
  host: <server IP address>,
  port: <port number>,
  key: fs.readFileSync('client.key'),
  cert: fs.readFileSync('client.crt'),
  ca: fs.readFileSync('ca.crt'),
  checkServerIdentity: function (host, cert) {
    return undefined;
  }  
};

const client = tls.connect(options, function(){
  if (client.authorized) {
    console.log("Connection authorized");
  } else {
    console.log("Connection not authorized: " + conn.authorizationError)
  }
  process.stdin.pipe(client);
  process.stdin.resume();
  client.emit('data','message')
});

client.setEncoding('utf8');

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

client.on('end', () => {
  server.close();
});

server.js

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

const options = {
  key: fs.readFileSync('server.key'),
  cert: fs.readFileSync('server.crt'),
  ca: fs.readFileSync('ca.crt'), 
  requestCert: true, 
  rejectUnauthorized: true  
};

const server = tls.createServer(options, function(socket){
  console.log('server connected',
              socket.authorized ? 'authorized' : 'unauthorized');
  socket.setEncoding('utf8');
  socket.pipe(socket);
  socket.emit('data','lol')
});

server.listen(<port number>,function(){
  console.log('listening')

})

server.on('connection',function(client){
  console.log('client connected')
  client.on('data',function(data){
    console.log(data)
  })
}) 

The server does output 'client connected' but does not do anything with the client.on() part, and I can not find another way to make the server listen for messages from the client. Is there a way to use the tls module so that I can make the client and server interact based on the messages they send and receive? Again, I do not want to use a browser.



via peter

No comments:

Post a Comment