Search code examples
node.jsstructbuffer

Node.js net socket on data event returns socket object


I am working with net.sockets for my project, and so far I can send information to the socket, but I'm having a headache trying to read from it. Although I've working with Node.js for a while now, it is my first time working with net.sockets and I find it tricky.

I am trying to validate a server and a port throught the socket, it is my simple example in the app, to then continue implementing the rest.

export function validate (host, port) {
  const socket = net.createConnection(port, host, () => {
    console.log('Socket connected....')
  })
  my_send(socket, struct.pack('>LL', 510, 0))
  const header = my_rec(socket, 8)
  ......
}

This is the function to send information to the socket, and it seems to be working OK

function my_send (socket_, msg) {
  let total_sent = 0
  while (total_sent < msg.length) {
    const msg_sliced = msg.slice(total_sent, msg.length)
    const sentOk = socket_.write(msg_sliced)
    if (!sentOk)
      throw new Error('RuntimeError: socket connection broken')
    total_sent = total_sent + msg_sliced.length
  }
}

my_send function returns this: � (<<<< I am assuming this is the buffer information)

Next, the function to read information from the socket

function my_rec (socket_, length) {
  let msg = ""
  while (msg.length < length) {
    const chunk = socket_.on('data', (data) => {
      console.log('data slice ' + data)
      return data
    })
    if (chunk === "")
      throw new Error('RuntimeError: socket connection broken')
    msg = msg + chunk
  }
  return msg
}

Notice that I'm outputing data received, but it is always a socket object. I am following the net.socket documentation, and examples here in SO, but nothing has worked so far.

I already tried this:

function my_rec (socket_, length) {
  let msg = ""
  socket_.setEncoding('utf8')
  while (msg.length < length) {
    const chunk = socket_.on('data', (data) => {
      console.log('data slice ' + data)
      return data.toString()
    })
    if (chunk === "")
      throw new Error('RuntimeError: socket connection broken')
    msg = msg + chunk
  }
  return msg
}

And this returns also the socket object: enter image description here

I see that this object has a property _pendingData with the buffer I need, but I can't access it.

Can anyone help me and tell me what am I doing wrong?


Solution

  • I finally managed to solve the issue. I refactored the my_rec function to look like this:

    function my_rec (socket_, length) {
      let msg = new Uint8Array(0)
      let chunk = ''
      socket_.on('data', data => {
        chunk = data.toString()
        if (chunk === '')
          throw new Error('RuntimeError: socket connection broken')
        msg = chunk
      })
      return msg
    }
    

    I realized I do not need the while loop, the socket receives the data and I can access it easily.

    It is working for me, I hope it helps some other people.