Nodejs Net Data event listener To wait for the right data

462 views Asked by At

I have a tcp client that receives defined message types from a server When the client writes it passes an identifier that comes with the message from the server in response to this. The data event listener should do something like this

sock.on('data', function (data) {
      //validate the data, check if identifier == to identifier in data
      if(true){
        return data
        //terminate listener
     }
     else{
       // wait for the next message
       // this should also exit upon a time out and terminate listener
     }
  });

How can i wait for the exact one after checking the data since several messages are written to the same socket for other listeners. After 4 seconds i want to exit even if the data in socket does not match the identifier

Please help.

1

There are 1 answers

0
Danstan On
      // initialize the expected  message identifier
      let expected = outgoing.getMti() 
      client.on('data', function (data) {
                //get the message identifier from data
                let incomingMTI = data.getMti()
                switch(incomingMTI){
                    case expected:
                        resolve (data)
                    default:
                        if((Date.now()-start)>8000){
                            reject({error:'timed out'})
                        }
                }
            });

So far i think the listener times out after 8 seconds. and send the error message. If you have a better way or see something i didn't please :-)