Ad

Returning Connected Socket Returns Null

- 1 answer

I am trying to create an client - server app on android. I want to have a class that initialize the socket and returns it to the main class. I don´t have any problems creating and connecting the socket (my server is handling the connection properly) but when I try to return that created socket to the main class it is null. What am I missing?

I have tried using AsyncTask.

This is the code of the main class:

public class MainActivity extends AppCompatActivity {
    private Socket socket;
    private SocketHandler sH;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sH = new SocketHandler();
        sH.start();
        socket = sH.getSocket();

        if(socket == null){
             System.out.println("null");
        }else{
            System.out.println("not null");
        }
    }
}

This is the code of the class that initialize the socket:

public class SocketHandler extends Thread {
    private Socket socket;

    public Socket getSocket(){
        return socket;
    }

    @Override
    public void run(){
        try{
            socket = new Socket("192.168.0.4", 9999);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
Ad

Answer

Thread are run in parallel which means it is NOT guaranteed that you socket connection would complete immediately, yet you falsely assume that and you step on classic race condition, because at the moment you call getSocket() the connection is still being established (but this process has not yet completed), therefore socket variable is still null as it was initialized upon creation of instance of your SocketHandler.

You need to synchronize the code, do a callback or (for testing purposes) either wait a bit before you call getSocket() or read couple of times (i.e. in a loop + some delay/timeout unless socket value is not null (but mind you need to expect null to be also valid value if socket connection fail).

Also, why you read the socket in main thread if you create in in separate thread? shouldn't you be doing all the socket work in that thread anyway?

Ad
source: stackoverflow.com
Ad