38 lines
784 B
JavaScript
38 lines
784 B
JavaScript
import * as net from 'net';
|
|
|
|
const hostname = '192.168.1.219';
|
|
const port = 29999;
|
|
|
|
function getBinarySize(string) {
|
|
return Buffer.byteLength(string, 'utf8');
|
|
}
|
|
|
|
function padLeft(size = 4, str = '') {
|
|
let remaining = size - str.length;
|
|
return '0'.repeat(remaining) + str;
|
|
}
|
|
|
|
export default function req(data, callback, errorCallback) {
|
|
let string_data = JSON.stringify(data);
|
|
let size = getBinarySize(string_data);
|
|
if (size > 9999) {
|
|
errorCallback("too long");
|
|
return;
|
|
}
|
|
|
|
let client = new net.Socket();
|
|
client.connect(port, hostname, () => {
|
|
let res = client.write(padLeft(4, `${size}`));
|
|
|
|
if (res) {
|
|
client.write(string_data);
|
|
}
|
|
client.destroy();
|
|
callback('success.');
|
|
});
|
|
|
|
client.on('error', (e) => {
|
|
client.destroy();
|
|
errorCallback(e);
|
|
});
|
|
}
|