netP5 (TCP/IP) and correct way to exit app?


#1

I anybody using netP5 from OSC5 package for TCP/IP under Android? I’m having some stabiliy issues with it. Specifically on exit: Sometimes, my app crashes on exit. I can see in Processing’s console that some code of netP5 has crashed (same readln thing, from memory). What is the correct way to exit an app?

In setup(), I create a netP5 listener:

import netP5.*;

NetListener Listener; 

void
setup
{
    ...

    // create listener for TcpClient; will receive NetMessages which contain the data. NetListener is an interface and requires to implement netEvent and netStatus. 
  
    Listener = new NetListener()
    {
        public void netEvent(NetMessage m) 
        {
            if (Client != null)
            {
                ClientIO = m.getString();
                
                if (ClientIO != null)
                {
                    ProcessReport(ClientIO);
                } 
            }
        }
        
        public void netStatus(NetStatus s)
        {
            ;
        }
    };

    ...
}

I open the TCP/IP connection via another thread (because netP5 functions can block for a very very long time if the IP is wrong). If that thread can create a client, it sets the global variable Client. My main thread shows a spinning wheel in the meantime - and an “X” button to abort.

    ...
    thread("TryIP");
    ...

void
TryIP()
{ 
    boolean   success = false;
    TcpClient client;
    
    try
    {
        client = new TcpClient(Listener, IP, Port, TcpServer.MODE_NEWLINE);
    }
    catch (Exception e)
    {
        client = null;
    }
    
    // try for 5s (5000ms) to send anything to see if the connection works

    if (client != null)
    {
        success = false;

        for (int n = 0; (n < 10) && (success == false); ++n, delay(500))
        {
            success = true;
                
            try
            {
                client.send("\n");
            }
            catch (Exception e)
            {
               success = false;
            }
        }
    }

    if (success)
    {
        Client  = client;

        ...
    }
    else   
    {
        if (client != null)
        {
            client.dispose();

            client = null;
        }
    }
}

For exit, I’ve tried a simple extit() - but that seems to leave the listener active: I have a println() in my TCP/IP receiving code (ProcessReport()), for debu purposes, and that is still called after exit, i.e. it prints stuff… Seems as if some thread is still running.

Alternatively, I’ve tried Client.dispose() and just setting Client = null. This works in the sense that the listener is no longer active but I have the occasional crash on exit.

void
terminate()
{
    Client   = null;
    Listener = null;
 
    exit();
}

Or:

void
terminate()
{   

    if (Client != null)
    {
        Client.dispose();
        
        Client  = null;
    }

    Listener = null;
 
    exit();
}