套接字设置超时使应用程序崩溃/尝试重新连接失败

时间:2018-10-13 18:40:56

标签: java android sockets exception client

我正在做一个用于从服务器接收数据的项目。直到我为套接字添加soTimeout行,此代码才能正常工作。

package com.lumineria.mywatertankr3;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;

import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.content.Intent;
import android.widget.TextView;
import android.widget.Toast;


import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;


public class MainActivity extends AppCompatActivity {

public static final String SETTINGS_PREF = "MyTankSettings";

TextView textViewNivel,textViewEstado;
String strNivel = "";
String ipAddressSaved="";

// Create the Handler object (on the main thread by default)
Handler handler = new Handler();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    textViewNivel = findViewById(R.id.nivel);
    textViewEstado = findViewById(R.id.status);

    // Restore preferences
    SharedPreferences settings = getSharedPreferences(SETTINGS_PREF, 0);

    // Levanto de memoria los valores de IP y Tiempo de Refresco
     ipAddressSaved = settings.getString("ip", "");

    // SI tengo un valor definido de IP intento la conexion
    if (!ipAddressSaved.equals(""))
    {
        Thread clientThread = new Thread(new ClientThread());
        clientThread.start();
    } else {
        Toast.makeText(getApplicationContext(),
                "No se definio IP del Server",
                Toast.LENGTH_LONG).show();
    }


}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_main, menu);
    return super.onCreateOptionsMenu(menu);
}


public class ClientThread  implements Runnable  {
    public void run() {
        try {
            while (true) {
                InetAddress serverAddr = 
InetAddress.getByName(ipAddressSaved);
                 Socket socket = new Socket(serverAddr, 10000);
// WHEN I ADD THIS LINE APP CRASHES
                // socket.setSoTimeout(10000);



                InputStreamReader reader = new InputStreamReader (socket.getInputStream());
                BufferedReader in = new BufferedReader( reader);
                String line;




                while ((line = in.readLine()) != null) {
                   strNivel = line;
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            textViewNivel.setText(strNivel);
                        }
                    });

                }
                in.close();
                socket.close();
                Thread.sleep(500);

            }
        } catch (SocketTimeoutException exception)  {
            textViewEstado.setText(textViewEstado.getText()+"1");
        } catch (IOException exception)  {
            textViewEstado.setText(textViewEstado.getText()+"2");
        } catch (Exception exception){
            textViewEstado.setText(textViewEstado.getText()+"3");
        }  finally {
            textViewEstado.setText(textViewEstado.getText()+"4");
        }
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_settings:
            Intent intent=new Intent(this,SettingsActivity.class);
            startActivity(intent);
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}



}

我做错了什么?有没有最好的方法来检查服务器是否不再可用?我想检查什么时候再也没有了,我希望断开连接并重新启动连接。

提前致谢

0 个答案:

没有答案