2016-05-12 6 views
3

これは私の2番目の投稿です。アンドロイドクライアントとPC上で実行されるJavaサーバーアプリケーションの間のソケット通信TCP/IPでこのような大きな問題が発生します。socket - Androidクライアント - JavaサーバーPCが詰まる

私がしようとするのは、クライアントアプリケーションからサーバーにボタンを押してから、クライアントアプリケーションに何度も回答を返すときに文字列を送信することです。この結果は、TextView私の顧客。

問題は、クライアントアプリケーションでサーバーに接続しようとすると接続が正常に実行されますが、ボタンを押してデータを送信するとクライアントアプリケーションが停止し、結果を表示する唯一の方法ですサーバーアプリケーションを停止しています。私は助けが必要です!私はAndroidが初めてです。ありがとう。

これは、単純なサーバーコードです:

import java.io.*; 
import java.net.*; 
import java.util.logging.Level; 
import java.util.logging.Logger; 

public class ServerSocks { 

private static ServerSocket myServer; 
private static Socket myClient; 
private static String msj_ToServer; 

public static void main (String args[]){ 

    try { 

     System.out.println("Bienvenido:\n"); 

     System.out.println("Por favor ingresar el nº de puerto de comunicación: "); 
     BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
     String portNumber_str = in.readLine(); 
     int portNumber = Integer.parseInt(portNumber_str); 
     myServer = new ServerSocket(portNumber); 

      if(myServer.isBound() == true){ 

      System.out.println("Iniciando servidor en el puerto: "+portNumber); 

      } 

      else{ 

      System.err.println("[E R R O R] : No se pudo crear 'LISTEN SOCKET'"); 
      System.exit(0); 

      } 

      while(true){ 

      System.out.println("Esperando algún cliente TCP en el puerto ["+portNumber+"]..."); 
      myClient = myServer.accept(); 

      if (myClient.isConnected()) { // if2 

      System.out.println("[D A T A] : El cliente ha sido aceptado IP-CLIENT\n"+""+ "IP Client address: "+myClient.getInetAddress()); 

      DataOutputStream outClient = new DataOutputStream(myClient.getOutputStream()); 

      DataInputStream inClient = new DataInputStream(myClient.getInputStream()); 
      msj_ToServer = inClient.readLine(); 
      System.out.println("Ha1 "+msj_ToServer); 

      try{ 


      if(msj_ToServer.equalsIgnoreCase("D")) { 
      System.out.println("HO "+msj_ToServer); 
      outClient.writeBytes("ON"); 
      outClient.flush(); 
      break;    

      } 

      }catch(IOException e){ 
      e.printStackTrace(); 
      } 

      if(msj_ToServer == "B" || msj_ToServer == "b"){ 

       System.out.println(msj_ToServer); 
       outClient.writeUTF("OFF"); 
       outClient.flush(); 
       break; 
       } 

       if(msj_ToServer == "C" || msj_ToServer == "c"){ 
       System.out.println(msj_ToServer); 
       outClient.writeUTF("xd"); 
       outClient.flush(); 
       break; 
       } 

       } // fin while inicio de lectura */ 

       } // fin msj1 

       } // fin while prueba 3 
       }// fin if2 


       } // fin while (true) superior 

      } catch (IOException ex) { 
       Logger.getLogger(ServerSocket.class.getName()).log(Level.SEVERE, null, ex); 
      ex.printStackTrace(); 
     } 

    }// fin main 

} // fin clase ServerSocks 

これは私のAndroidのクライアントアプリケーションのMain.javaの一部(I "が送信されるボタン(「ステータス」ボタン)でプローブしていますですD "文字列をサーバーに送り、サーバーは応答として" ON "を返します)。ここ

public class MainActivity extends Activity implements OnClickListener { 

private Button ledOnButton; 
private Button ledOffButton; 
static ToggleButton toggleButton; 
static EditText statusEditText; 
private Button status; 
static TextView prueba; 

static Socket clientSocket; 
static String data; 

static String dato; 

static PrintStream os; 
static DataInputStream is; 
static DataInputStream inputLine; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    if (android.os.Build.VERSION.SDK_INT > 9) { 
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
     StrictMode.setThreadPolicy(policy); 
    } 

    ledOnButton = (Button) findViewById(R.id.ledOnButton); 
    ledOnButton.setOnClickListener(this); 

    ledOffButton = (Button) findViewById(R.id.ledOffButton); 
    ledOffButton.setOnClickListener(this); 

    toggleButton = (ToggleButton) findViewById(R.id.toggleButton); 
    toggleButton.setOnClickListener(this); 

    status = (Button) findViewById(R.id.statusButton); 
    status.setOnClickListener(this); 

    statusEditText = (EditText) findViewById(R.id.statusEditText); 

    // prueba con textView 

    prueba = (TextView) findViewById(R.id.textView_Prueba); 

} // fin OnCreate 

@Override 

public void onClick(View arg0) { 

    AsyncAction object = new AsyncAction(); 
    final String salida_dato; 


switch (arg0.getId()) { 

    case R.id.toggleButton: 


     if (toggleButton.isChecked()) { 

      object.conexion_socket(); 


     } 

     if (!toggleButton.isChecked()) { 

      object.desconexion_socket(); 

     } 


     break; 

    case R.id.ledOnButton: 


     if ((MainActivity.toggleButton.isChecked())) { 

      object.ledOnButton(); 
     } 

     break; 

    case R.id.ledOffButton: 

     if ((toggleButton.isChecked())) { 

      object.ledOffButton(); 
     } 

     break; 

    case R.id.statusButton: 

私は

@Override 
    protected String doInBackground(Void... args) { 

     conexion_socket(); 

     ... 


    }//fin doInBackground 

(私はそう思う)接続がasynchTasksと、バックグラウンドで実行されているサーバー

 if ((toggleButton.isChecked())) { 


      if (clientSocket != null && os != null && is != null) { 

       try { 

        final String responseLine; 
        // String data = "D"; 
        //os.write(data.getBytes()); 
       os.println("D"); 


        while ((responseLine = is.readLine()) != null) { 
         System.out.println(responseLine); 


         runOnUiThread(new Runnable() { 
          public void run() { 
           MainActivity.prueba.setText(responseLine); 
           os.flush(); 

          } 
         }); 

         break; 


        } 

        os.close(); 
        is.close(); 
        clientSocket.close(); 

       } //fin try 

       catch (UnknownHostException e) { 
        System.err.println("Trying to connect to unknown host: " + e); 
       } catch (IOException e) { 
        System.err.println("IOException: " + e); 
       } 

、ここに "D" の文字列を送信しようとここで私はソケット接続を作成するために使用した接続方法です。

public void conexion_socket(){ 

     try { 

      MainActivity.clientSocket = new Socket("192.168.2.80", 30000); 

      try { 

       MainActivity.os = new PrintStream(MainActivity.clientSocket.getOutputStream()); 
       MainActivity.is = new DataInputStream(MainActivity.clientSocket.getInputStream()); 
       MainActivity.inputLine = new DataInputStream(new BufferedInputStream(System.in)); 

      } // fin try 

      catch (IOException e){ 

       System.err.println("algo anda al con los i/o ..."); 

      } // fin catch 




     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     if (MainActivity.clientSocket.isConnected()) { 
      MainActivity.statusEditText.setText("OK connection"); 
     } 
    } 

誰でもこの通信を行う方法を教えていただけたら、どうかありがとう!

答えて

2
if(myServer.isBound() == true){ 

これは、この時点では間違いである可能性があります。テストとブロックelseを削除します。あなたはServerSocketをポート番号=>で構成しました。これはバインドされています。

 else{ 
     System.err.println("[E R R O R] : No se pudo crear 'LISTEN SOCKET'"); 
     System.exit(0); 
     } 

到達不能です。削除します。

 while(true){ 
     System.out.println("Esperando algún cliente TCP en el puerto ["+portNumber+"]..."); 
     myClient = myServer.accept(); 
     if (myClient.isConnected()) { // if2 

もう一度これは誤りである可能性があります。ソケット=>接続されています。無駄なテストを書いてはいけません。

 System.out.println("[D A T A] : El cliente ha sido aceptado IP-CLIENT\n"+""+ "IP Client address: "+myClient.getInetAddress()); 
     DataOutputStream outClient = new DataOutputStream(myClient.getOutputStream()); 
     DataInputStream inClient = new DataInputStream(myClient.getInputStream()); 
     msj_ToServer = inClient.readLine(); 
     System.out.println("Ha1 "+msj_ToServer); 
     try{ 

     if(msj_ToServer.equalsIgnoreCase("D")) { 
     System.out.println("HO "+msj_ToServer); 
     outClient.writeBytes("ON"); 

ここではバイトを書きますが、行終端は使用していません。クライアント内の対応するコードはreadLine()を使用しているため、永遠にブロックされます。この文字列に行終端文字を追加します。

 outClient.flush(); 

冗長。削除します。 DataOutputStreamはバッファされず、いずれもSocket.getOutputStream()であるため、どちらのフラッシュも何もしません。

 }catch(IOException e){ 
     e.printStackTrace(); 
     } 

     if(msj_ToServer == "B" || msj_ToServer == "b"){ 

      System.out.println(msj_ToServer); 
      outClient.writeUTF("OFF"); 

writeUTF()で使用されているバイト、行、または特殊な書式を書いていますか?クライアントの対応するコードはreadLine()を使用します。私は、あなたがreadLine()、またはwriteUTF()/readUTF()で読むための行を書くことを標準化することをお勧めします。それらを混在させることはできません。

  outClient.flush(); 

上記を参照してください。削除します。

  if(msj_ToServer == "C" || msj_ToServer == "c"){ 
      System.out.println(msj_ToServer); 
      outClient.writeUTF("xd"); 

上記を参照してください。

  outClient.flush(); 

上記を参照してください。

 MainActivity.clientSocket = new Socket("192.168.2.80", 30000); 

     try { 

      MainActivity.os = new PrintStream(MainActivity.clientSocket.getOutputStream()); 
      MainActivity.is = new DataInputStream(MainActivity.clientSocket.getInputStream()); 
      MainActivity.inputLine = new DataInputStream(new BufferedInputStream(System.in)); 

     } // fin try 
     catch (IOException e){ 
      System.err.println("algo anda al con los i/o ..."); 
     } // fin catch 

これらのコード行をtryブロック内に配置する理由はありません。あなたはすでに1つに入っています。

if (MainActivity.clientSocket.isConnected()) { 

このテストは、この時点では間違いである可能性があります。ソケットが構築されていれば、それは接続されています。

誤って構造化された例外処理が原因で、nullになることがあります。これに続くブロックは、ブロックを囲む前のtryブロック内にある必要があります。

一般的に、内部のすべてのブロックtry/catchを取り除く必要があります。先のtryブロック内のコードの成功に依存するコードは、ブロックtry内にあるはずです。

+0

ありがとうございます!私はあなたの推薦とアドバイスに従って、私はあなたの結果を知らせます!私は最終的にコミュニケーションを得ることを期待しています:) thankssss –

関連する問題