2016-08-01 17 views
1

私はアンドロイドにjavaソケットを持っています。私はいくつかの問題があり、それらを解決するための助けが必要です。Androidソケットの原則と例外

私はサーバーソケットにボトムコードで接続していますが、すべて問題ありません。しかし、コール切断メソッドと再度接続しようとすると、私は問題を直したsocket is nullまたはBufferedReaderオブジェクトは、切断後に常にnullを返し、再び接続します。多分私の切断方法は間違っています。どんな時にインターネットを壊して再接続するようなソケットを切断する最良の方法は何ですか?

ソケットの接続と切断のコードです。

public class HelperSocket { 

public static Socket socket = null; 
public static DataOutputStream writer = null; 
public static BufferedReader reader = null; 
public static DataInputStream inputStream = null; 
public static final String SOCKET_ADDRESS = "aUrlForSocket"; 
public static final int SOCKET_PORT = 6000; 
public static final int SOCKET_TIMEOUT = 30000; 
public static Thread clientThread; 
public static boolean isConnected = false; 

public static boolean connect() { 
    Utils.Log("StartConnect"); 
    if (!isConnected) { 
     clientThread = new Thread(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        InetAddress address = InetAddress.getByName(HelperSocket.SOCKET_ADDRESS); 
        socket = new Socket(address.getHostAddress(), SOCKET_PORT); 

        isConnected = true; 
        socket.setSoTimeout(SOCKET_TIMEOUT); 

        writer = new DataOutputStream(socket.getOutputStream()); 
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
        inputStream = new DataInputStream(socket.getInputStream()); 

        while (HelperSocket.isConnected) { 
         Utils.Log("onWhile" + reader.hashCode()); 
         try { 

          if (reader.readLine() != null) { 
           Utils.Log(reader.readLine() + ""); 
          } else { 
           Utils.Log("getNullFromServer"); 
           //data get null here :) 
           disconnect(); 
          } 
         } catch (IOException e) { 
          Utils.Log("ProblemOnReadData" + e.getMessage()); 
          e.printStackTrace(); 
         } 
        } 
       } catch (IOException e) { 
        Utils.Log("SocketProblemAt connect:" + e.getMessage()); 
        e.printStackTrace(); 
       } 
      } 
     }); 
     clientThread.start(); 
    } 

    return true; 
} 

public static boolean disconnect() { 
    isConnected = false; 
    if (!clientThread.isInterrupted()) 
     clientThread.interrupt(); 
    if (socket != null) { 
     Utils.Log("SocketAndAllObjectCleared"); 
     try { 
      socket.shutdownInput(); 
      socket.shutdownOutput(); 
      socket = null; 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     /* stream = null; 
     reader = null;*/ 
    } 
    return false; 
} 


} 

私は、ネットワーク接続の変更にレシーバを作成して、デバイスがインターネットに接続し、インターネット接続が確立したときに再接続できない時にソケットを切断する必要があります。

受信機:

ネットワークの状況を確認する
public class BroadcastChangeNet extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     if (Utils.isNetworkConnected()) { 
      HelperSocket.connect(); 
      Utils.Log("NetWorkConnect"); 
     } else { 
      HelperSocket.disconnect(); 
      Utils.Log("NetWorkDisConnect"); 
     } 
    } 
} 

:あなたは、単に以下、saprate Javeクラスを作成する必要が私の視点から

public static boolean isNetworkConnected() { 
     ConnectivityManager conMgr = 
       (ConnectivityManager) ApplicationClass.context.getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo i = conMgr.getActiveNetworkInfo(); 
     if (i == null) 
      return false; 
     if (!i.isConnected()) 
      return false; 
     if (!i.isAvailable()) 
      return false; 
     return true; 
    } 
+0

あなたはそれをシャットダウンし、ソケットを閉じていないする必要があります。あなたは行を読んでいて、それを投げ捨てています。 Javaチュートリアルのカスタムネットワークセクションを見ておく必要があります。 – EJP

+0

@EJPもし私がソケットを閉じたら、それを再利用できますか? closeソケットがそれを再び開くことができる場合はsomwhereを読んでください。 – javaddroid

+0

シャットダウンしたり閉じると再利用することはできません。新しいものを作成する必要があります。ありがとう@kintanpatel。 – EJP

答えて

1

は私が正常にテスト私のコードは、

です
import android.content.Context; 

import java.io.BufferedReader; 
import java.io.DataOutputStream; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.net.Socket; 
import java.net.SocketException; 
import java.net.UnknownHostException; 

/** 
* Created by Kintan Patel on 01-08-2016. 
*/ 
public class SocketConnection { 
    private Socket socket = null; 
    private OutputStream outputStream; 
    private DataOutputStream dataOutputStream; 
    private SessionHelper helper; 

    public String EstablishConnection(String token) { 
    // token = your message that write on socket server 
     String response; 
     try { 

      //socket = new Socket("192.168.0.24", 2129); // Testing Server 
      socket = new Socket("Your IpAddress", PORT NO); 
      outputStream = socket.getOutputStream(); 
      dataOutputStream = new DataOutputStream(outputStream); 
      dataOutputStream.writeUTF(token); 
      BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
      response = br.readLine(); 

     } catch (UnknownHostException e) { 
      e.printStackTrace(); 
      response = "UnknownHostException: " + e.toString(); 
      return null; 

     } catch (SocketException e) { 
      e.printStackTrace(); 
      response = "Sorry Fail to connect"; 
      return null; 

     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      // e.printStackTrace(); 

      response = "Sorry Fail to connect"; 
      return null; 

     } catch (Exception e) { 
      e.printStackTrace(); 
      response = "Server Break"; 
      return null; 

     } finally { 
      if (socket != null) { 
       try { 
        socket.close(); 
        outputStream.close(); 
        dataOutputStream.close(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
     } 
     return response; 
    } 
} 

あなたのメインクラスから、単にSocketConnectionクラスのオブジェクトを作成し、あなたは以下よりAsynkTaskを使用したい場合はEstablishConnection()メソッド、

eg : 

    SocketConnection connection = new SocketConnection(); 
     String token = "message that you want to write on server"; 
     String response = connecation.EstablishConnection(token); 

を使用AsynkTaskコードです:

private class ActivationTask extends AsyncTask<String, String, String> { 

     @Override 
     protected String doInBackground(String... params) { 
      SocketConnection connection = new SocketConnection(); 
      String token = "getActivation|" + params[0] + "|"; 
      return connection.EstablishConnection(token); 
     } 


     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      progressDialog.show(); 
     } 

     @Override 
     protected void onPostExecute(String s) { 
      super.onPostExecute(s); 
      progressDialog.dismiss(); 
      if (s != null) { 
       Log.e("RESULT" , s); 



      } 
     } 
    } 
+0

ちょっと質問:私がソケットを閉じると、私は再び開き直して使用できますか? – javaddroid

+1

はい、もう一度開くことができます。 – Kintanpatel