bemeyer
bemeyer

Reputation: 6231

TCPsending crashes the App if server is down

i wrote a Server for our global Leadbord which actually works now. I can send data to it if it's active. But if it's down my app does not stop. I dont get a solution for it i hope you can help me. Here is the sending:

public void saveToDatabase(LeadboardElement element2) {
    final LeadboardElement element = element2;
    send = false;
    // Need to be a thread! else android blocks it because it could take to
    // long to send!
    this.thread = new Thread() {
        public void run() {
            try {
                Socket soc = new Socket(Config.TCP_SERVERNAME_IP,
                        Config.TCP_PORT);
                DataOutputStream out = new DataOutputStream(
                        soc.getOutputStream());
                DataInputStream in = new DataInputStream(
                        new BufferedInputStream(soc.getInputStream()));

                // to call the save statement!
                out.writeInt(0);
                // give the stuff
                out.writeUTF(element.getName());
                out.writeInt(element.getLevel());
                out.writeInt(element.getKillPoints());

                // close it
                out.close();
                in.close();
                soc.close();
                send = true;
                //join at every error
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    // start it
    thread.start();

    // join thread
    if (!send) {
        boolean retry = true;
        while(retry)
        try {
            this.thread.join();
            retry = false;
            Log.w(TAG, "sending to server stopped!");
        } catch (InterruptedException e2) {
            Log.w(TAG, "Thread could not be joined");
        }
    }
}

I noticed that i need to do it in a thread since API 5 so it works like this. It's called at the end of an Game if the player touches the screen. Everything get stopped and the data is sent to the Server. If hes down it does not work we stuck in the fade to black. I guess i need something like a timeout. I tried it with a CountDownTimer but this acutally does not solve the problem.

Thanks alot!

Upvotes: 0

Views: 83

Answers (1)

Gjordis
Gjordis

Reputation: 2550

Changing the way you initialize the socket, you can set a timeout.

Socket s1 = new Socket();
s1.setSoTimeout(200);
s1.connect(new InetSocketAddress("192.168.1." + i, 1254), 200);

Add a timeout when creating a new Socket

Upvotes: 2

Related Questions