Rapsssito / react-native-tcp-socket

React Native TCP socket API for Android, iOS & macOS with SSL/TLS support.
MIT License
304 stars 80 forks source link

synchronously connecting to multiple devices #143

Closed rockneverdies55 closed 2 years ago

rockneverdies55 commented 2 years ago

I need to send the same data blob to multiple devices in the local network.

const theDataToSend = { ... };
const targetDevices = [{ host: h1, port: p1}, {host: h2, port: p2}, {host: h3, port: p3}];
for(let i = 0; i < targetDevices.length; ++i) {
  const currDevice = targetDevices[i];
  const isSuccess = await sendDataViaTcpSocket(theDataToSend, currDevice.host, currDevice.port);
  console.log(host + ': ' + isSuccess);
}

const sendDataViaTcpSocket = async (data, host, port) => {
  const p = new Promise(resolve => {
    let client = TcpSocket.createConnection({host, port}, () => {
      client.write(data);
      client.destroy();
      resolve(true);
    });
  }); // promise
  return p;
}

After the first target device receives the data, app completely exits suddenly. Is there anything suspicious in my code that catches your attention immediately that could be improved? I'm very new to sockets idea and just can't figure out the culprit in this case.

rockneverdies55 commented 2 years ago

Started to call client.destroy() within the callback of client.write() and that seems to fix the issue.

const sendDataViaTcpSocket = async (data, host, port) => {
  const p = new Promise(resolve => {
    try {
      client = TcpSocket.createConnection({host, port}, () => {
        client.write(data, 'utf8', async () => {
          client.destroy();
          resolve(true);
        });
      });
    } catch (e) {
      resolve(false);
    }
  });//promise
  return p;
};