0

below is my code which may not be good as i am still learning nodejs / javascript.

I want to make this set of code to be a component or module whereby the user of this module can

  1. call the function and retrieve the value (getRowID(tableName))
  2. it can automatically check if disconnected, it will create the UDP to find the server and connect to via TCP to call the function. (i m now using a timer to check this).

Currently, the result from the getRowID is returned in tcpDataHandler function. How can i return the value via the getRowID function for the user to call it?

As you can see in tcpConnectedHandler function, i tried to call the function getRowID function but it returned "undefined" but the result is returned later. Is there a way to wait for the result to return using await function?

please advise and comment.

regards chris

const dgram = require('dgram');
const net = require("net")
const ip = require('ip');

let socketConnected=false;
const aIP = ip.address() + '\0';
//const aIP='192.168.1.10\0';
const aServerPort=25961;
const aServerIP='192.168.1.241';
var socket1=null;
var client1=null;

setInterval(()=>checkConnection(), 5000);

function checkConnection() {
    if (!socketConnected) {
        createUDPConnection();
    }
}

function createUDPConnection() {
    // cc : set it to null for any previous created instances
    // cc : so that the garbage collector will clear it
    socket1=null;
    socket1 = dgram.createSocket('udp4');
    socket1.on('listening', udpListenHandler);
    socket1.on('message', (msg, rinfo) => udpMessageHandler(msg, rinfo));
    socket1.bind();        
}

function createTCPConnection(aIP, aPort) {
    // cc : set it to null for any previous created instances
    // cc : so that the garbage collector will clear it
    client1=null;
    client1 = new net.Socket();
    client1.on('connect', tcpConnectedHandler);
    client1.on('data', (msg) => tcpDataHandler(msg));
    client1.on('timeout', tcpTimeoutHandler);
    client1.on('drain', tcpDrainHandler);
    client1.on('error', tcpErrorHandler);
    client1.on('close', tcpCloseHandler);
    try {
        client1.connect(aPort, aIP);
    }
    catch (err)
    {

    }
}

function udpListenHandler() {
    let l_address = socket1.address();
    console.log('Listening on ' + l_address.address + ' Port: ' + l_address.port);
    let l_port = l_address.port;
    const buf = Buffer.alloc(26);
    let l_index = buf.write('SOREQ\0','utf-8');
    l_index = buf.writeInt32BE(l_port, l_index);
    buf.write(aIP, l_index);
    console.log(buf);
    socket1.send(buf,aServerPort, aServerIP, (err, aNumBytes) => {
        if (err) 
          throw err;
    })
}

function udpMessageHandler(msg, rinfo) {
    console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
    let l_Header = msg.toString('utf-8', 0, 5);
    let l_Port = msg.readInt32BE(6);
    let l_IP = msg.toString('utf-8', 10).trim();
    console.log(`Header ${l_Header} Port: ${l_Port} IP: ${l_IP}`);
    createTCPConnection(l_IP, l_Port);
}

function tcpConnectedHandler() {
    console.log('Connected to server');
    socketConnected=true;
    console.log('Data returned: ' + getRowID('ASP'));
}

function tcpDataHandler(msg) {
    console.log('TCP Data received');
    console.log(msg);
    let l_msgLen = msg.readInt16BE(0);
    if (msg.length >= l_msgLen) {
        return msg.readInt32BE(4);
    }
}

function tcpTimeoutHandler() {
    console.log('TCP Timeout');
}

function tcpDrainHandler() {
    console.log('TCP drain');
}

function tcpErrorHandler() {
    console.log('TCP Error');
    socketConnected = false;
}

function tcpCloseHandler() {
    console.log('TCP Closed');
    socketConnected=false;
}

function getRowID(aTableName) {
    if (aTableName.trim() == "")
        return -1;
    if (!socketConnected)
        return -1;
    let l_table = aTableName + '\0'
    let l_len = l_table.length + 4;
    let l_buf = Buffer.alloc(l_len);
    let l_index = l_buf.writeInt16BE(l_len,0);
    l_index = l_buf.writeInt8(0, l_index);
    l_index = l_buf.writeInt8(0, l_index);
    l_buf.write(l_table, l_index, l_table.length, 'utf-8');
    console.log(l_buf);
    client1.write(l_buf, 'utf-8', ()=>{
        console.log('Sent');
    });
}

======= Result =============

Listening on 0.0.0.0 Port: 59560
<Buffer 53 4f 52 45 51 00 00 00 e8 a8 31 39 32 2e 31 36 38 2e 31 2e 31 30 00 00 00 00>
server got: SORESei192.168.1.241 from 192.168.1.241:25961
Header SORES Port: 25961 IP: 192.168.1.241
Connected to server
<Buffer 00 08 00 00 41 53 50 00>
**Data returned: undefined**
Sent
TCP Data received
<Buffer 00 08 00 00 00 00 00 13>

===== End Result ===============

  • Are you asking how to design a custom IP protocol (question body), or asking how to write a reusable module (question title)? – Bergi May 22 '21 at 08:20
  • hi, i am asking how to write a reusable module as well how can i re-direct the tcp data back to my function after sending out the tcp message. any help? – Chris C May 22 '21 at 09:12
  • Ah, now I see. In general, the function that the API user calls would either take a callback or return a promise (or, rarely, return an event emitter). To make it reusable, don't use global variables, keep all the state local in the function (which might mean nested functions for declaring the handlers). – Bergi May 22 '21 at 12:53
  • Hi, how do I return a call back for the getRowID? Its calling a TCP socket and it will wait to get back a value from the TCP data event. How can I return this value from the TCP data event to the function getRowID and then return it to user who calls it? – Chris C May 24 '21 at 03:50
  • I said *take* a callback, not *return* a callback. You cannot immediately `return` anything, that's the whole point. https://stackoverflow.com/q/14220321/1048572 – Bergi May 24 '21 at 11:14
  • As i am still new to javascript, how do i take a callback when i call the getRowID which send data via TCP socket and the return result from TCP socket will become the callback of this getRowID? Is there an example i can try to code with? – Chris C May 26 '21 at 07:12

0 Answers0