Created
December 13, 2021 18:34
-
-
Save walterspieler/28ca3e8a2ef19ef37245b2dd5dab3a7b to your computer and use it in GitHub Desktop.
Client TLS Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const tls = require('tls') | |
const fs = require('fs') | |
const PORT = 6001 | |
const HOST = '0.0.0.0' | |
module.exports = (app) => { | |
const Xml = app.drivers.xml | |
const Encoder = app.drivers.encoder | |
const { handleInput, initiate } = app.controllers.pos | |
// Pass the certs to the server and let it know to process even unauthorized certs. | |
const options = { | |
// passphrase: 'test', | |
//key: fs.readFileSync(socket.key), | |
//cert: fs.readFileSync(socket.cert), | |
// Necessary only if the server uses a self-signed certificate. | |
ca: [fs.readFileSync(app.config.socket.cert)], | |
rejectUnauthorized: false, | |
strictSSL: false, | |
// Necessary only if the server's cert isn't for "localhost". | |
checkServerIdentity: () => { | |
return null | |
}, | |
} | |
const _decode = async (data) => { | |
let decoded = Encoder.decodeHex(data.toString().substr(8)) | |
console.log('Received decoded: ', decoded) | |
let content = await Xml.parse(decoded) | |
console.log('Received content: ', content) | |
return content | |
} | |
const client = tls.connect(PORT, HOST, options, function () { | |
// Check if the authorization worked | |
if (client.authorized) { | |
console.log('Connection authorized by a Certificate Authority.') | |
} else { | |
console.log('Connection not authorized: ' + client.authorizationError) | |
} | |
initiate(client) | |
}) | |
client.setEncoding('hex') | |
client.on('data', async function (data) { | |
// Verify everything went well | |
const content = await _decode(data) | |
handleInput(client, content) | |
// Close the connection after receiving the message | |
// client.end() | |
}) | |
client.on('close', function () { | |
console.log('Connection closed') | |
}) | |
// When an error ocoures, show it. | |
client.on('error', function (error) { | |
console.error('Client Error', error) | |
// Close the connection after the error occurred. | |
client.destroy() | |
}) | |
return client | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment