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

Attempt to invoke virtual method 'java.io.OutputStream' java.net.Socket.getOutputStream on a null object reference. #146

Closed sergeushenecz closed 2 years ago

sergeushenecz commented 2 years ago

Description

When I click for the first time everything is fine. Sometimes I click a second time and it's also good, but there is such a random error

Steps to reproduce

Steps to reproduce the behavior:

const client = TcpSocket.createConnection({
            host: printer.ip,
            port: printer.port,
          }, () => {
            client.write(data);
            client.destroy();
          });

          client.on('error', (error) => {
          });

          client.on('close', () => {
          });
  });

Current behavior

I have print btn. Attempt to invoke virtual method 'java.io.OutputStream' java.net.Socket.getOutputStream on a null object reference.

Expected behavior

Code to need works.

Screenshots

2022-03-27 22 51 54

Relevant information

OS android
react-native 0.64.3
react-native-tcp-socket 5.6.0
Rapsssito commented 2 years ago

@sergeu90, you must take into account that socket.write() is asynchronous, so, in your code, socket.destroy() might be called first. This will destroy the socket and then try to write to it. That's why you get that error.

A workaround would be to use the callback provided by socket.write() to make sure you destroy the socket after writing.

sergeushenecz commented 2 years ago

@Rapsssito Thanks a lot for helping. It is working.

 client.write(data, null, () => {
              client.destroy();
            });
Rapsssito commented 2 years ago

Glad it worked! I will close the issue now.