2016-08-03 18 views
-2

私は、AndroidアプリケーションをクライアントとしてSocketに基づいてサーバーに文字列を送信すると想像しています。android socket write error

まず、EditTextと送信ボタンを使用して動作するかどうかを確認するための小さなテストプログラムを作成します。 PCは文字列を受け取ることができます。次に、MainActivityと書くと、SocketActivityがbutton.onclickイベントで開きます。仕事はできません。

マイcode..theソケット部分

import java.io.BufferedWriter; 
    import java.io.IOException; 
    import java.io.OutputStreamWriter; 
    import java.io.PrintWriter; 
    import java.net.Socket; 
    import java.net.UnknownHostException; 
    import android.app.ActionBar; 
    import android.app.Activity; 
    import android.os.Bundle; 
    import android.text.TextUtils; 
    import android.util.Log; 
    import android.view.View; 
    import android.view.View.OnClickListener; 
    import android.widget.Button; 
    import android.widget.Toast; 
    public class LightControlActivity extends Activity { 
    private Button mBtnSend;     
    private static final String TAG = "com.ldgforever.controlbywifi"; 
    private String mIPAdress; 
    private int mPortNumber; 
     String ip="192.168.155.1"; 
     int port=1920; 
     Socket socket = null; 

    private String mSendMsg = "test"; 

    public static final String EXTRA_RECEIVE_IP = 
      "com.ldgforever.controlbywifi.receive_ip"; 
    public static final String EXTRA_RECEIVE_PORT = 
      "com.ldgforever.controlbywifi.receive_port"; 

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

     ActionBar actionBar = getActionBar(); 
     actionBar.setSubtitle("灯光管控"); 

     mIPAdress = getIntent().getStringExtra(EXTRA_RECEIVE_IP); 
     mPortNumber = Integer.parseInt(getIntent() 
       .getStringExtra(EXTRA_RECEIVE_PORT)); 

     mBtnSend = (Button)findViewById(R.id.send_data); 
     mBtnSend.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      SetOnClick(); 
      } 
    }); 
     } 
     private void SetOnClick() 
     {  
      // TODO Auto-generated method stub 
     try { 
       if(!TextUtils.isEmpty(mSendMsg)) 
         SendMsg(ip,port,mSendMsg); 
       else 
       { 
    Toast.makeText   (LightControlActivity.this,"msg is EMPTY!!", Toast.LENGTH_LONG).show(); 
       } 
     } catch (UnknownHostException e) { 
         // TODO Auto-generated catch block 
         Toast.makeText(LightControlActivity.this,"!UnknownHostException!", Toast.LENGTH_LONG).show(); 
         e.printStackTrace(); 
     } catch (IOException e) { 
         // TODO Auto-generated catch block 
         Toast.makeText(LightControlActivity.this,"!IOException!", Toast.LENGTH_LONG).show(); 
         e.printStackTrace(); 
     }catch (Exception e) { 
         // TODO Auto-generated catch block 
         Log.e(TAG, "Exception"); 
         Toast.makeText(LightControlActivity.this,"!Exception!", Toast.LENGTH_LONG).show(); 
         e.printStackTrace(); 
      } 

     } 

     public void SendMsg(String ip,int port,String msg) throws UnknownHostException, IOException 
     { 
    try 
    { 
     socket = new Socket(); 
     socket=new Socket(ip,port); 
     PrintWriter writer = new PrintWriter(new BufferedWriter 
       (new OutputStreamWriter(socket.getOutputStream()))); 
      // BufferedWriter writer=new BufferedWriter(new OutputStreamWriter 
      //    (socket.getOutputStream())); 
      //  writer.write(msg); 
     writer.println(msg); 
     writer.flush(); 
     writer.close();  
     socket.close(); 
    } 
    catch(UnknownHostException e) 
    { 
     Log.e(TAG, "UnknownHostException"); 
     e.printStackTrace(); 
    } catch (IOException e) 
    { 
     Log.e(TAG, "IOException"); 
     e.printStackTrace(); 
    } 
} 

エラーがSetOnClick()キャッチ(例外)で発生した私は、その理由を見つけるcan`t

私のサーバーコード

import java.io.BufferedReader; 
    import java.io.BufferedWriter; 
    import java.io.InputStreamReader; 
    import java.io.OutputStreamWriter; 
    import java.io.PrintWriter; 
    import java.net.ServerSocket; 
    import java.net.Socket; 

    public class TCPDesktopServer implements Runnable{ 


    public static final String SERVERIP = "192.168.155.1"; 

    public static final int SERVERPORT = 1920; 


    public void run() { 

     try { 

      System.out.println("S: Connecting..."); 

      ServerSocket serverSocket = new ServerSocket(SERVERPORT); 

      while (true) { 

        Socket client = serverSocket.accept(); 

        try { 

       BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); 

         String str = in.readLine(); 

         System.out.println("S: Received: '" + str + "'"); 

        } catch(Exception e) { 

         System.out.println("S: Error"); 

         e.printStackTrace(); 

        } finally { 

         client.close(); 

         System.out.println("S: Done."); 

        } 

      } 

      } catch (Exception e) { 

      System.out.println("S: Error"); 

      e.printStackTrace(); 
     } 
    } 

     public static void main (String a[]) { 

     Thread ServerThread = new Thread(new TCPDesktopServer()); 

     ServerThread.start(); 
    } 
} 

私はインターネット許可を追加しました。 …… 助けを求める……!

+0

)この

 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads().detectDiskWrites().detectNetwork() .penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects().detectLeakedClosableObjects() .penaltyLog().penaltyDeath().build()); 

は(のonCreateでこれを追加し解決するためにスタックトレースは何ですか? –

+0

'Can not work'と 'error occurred'は問題の説明ではありません。 – EJP

答えて

0

AsyncTaskを使用して、サーバーへのソケット呼び出しを行うことができます。

private class SendData extends AsyncTask<Void, Void, Void> { 

     String ip; 
    int port; 
    String msg; 

    SendData(String ip,int port,String msg) 
    { 
     this.ip = ip; 
     this.port = port; 
     this.msg = msg; 
    } 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      // Showing progress dialog 


     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 
try 
{ 
    socket = new Socket(); 
    socket=new Socket(ip,port); 
    PrintWriter writer = new PrintWriter(new BufferedWriter 
      (new OutputStreamWriter(socket.getOutputStream()))); 
     // BufferedWriter writer=new BufferedWriter(new OutputStreamWriter 
     //    (socket.getOutputStream())); 
     //  writer.write(msg); 
    writer.println(msg); 
    writer.flush(); 
    writer.close();  
    socket.close(); 
} 
catch(UnknownHostException e) 
{ 
    Log.e(TAG, "UnknownHostException"); 
    e.printStackTrace(); 
} catch (IOException e) 
{ 
    Log.e(TAG, "IOException"); 
    e.printStackTrace(); 
} 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      super.onPostExecute(result); 
      // Dismiss the progress dialog 

     } 

    } 

あなたはこのように呼んで、単に合格IP、ポート、およびメッセージをサーバーにデータを送信するために、これはそう、バックグラウンドで行われることができ、これは動作するはずです:

// Calling async task to send data 
    new SendData (ip,port,mSendMsg).execute(); 
0

これは動作しません。

あなたはドメインのGUIスレッドで実行されますクリックでハンドラにSetOnClick()を呼ぶようあなたは(LogCat、アプリのクラッシュではっきりと見える。なぜあなたは言わなかった?)NetworkOnMainThreadExceptionを持っています。

run()new thread()SetOnClick();を入れます。

+0

申し訳ありません......あなたは正しいです...... LogCatは、System.err android.os.NetwoekOnMainThreadException ...... –

0

は別の方法を探します