2016-08-03 74 views
-2

我想象一下,Android應用程序作爲客戶端發送String給服務器,PC基於Socket。android套接字寫錯誤

首先,我寫一個小測試程序,看它是否可以通過使用EditText和發送按鈕來工作。 PC可以接收字符串。然後我寫一個MainActivity通過button.onclick事件打開SocketActivity。它不起作用。

我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()趕上(例外),我不能老是找出原因

我的服務器代碼

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(); 
    } 
} 

我已添加Internet權限。 …… 請求幫忙……!

+0

什麼是堆棧跟蹤? –

+0

'無法工作'和'發生錯誤'不是問題描述。 – 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

它不能工作。

你有一個NetworkOnMainThreadException(清晰可見在logcat的和你的應用程序崩潰。你爲什麼不知道?),你在對運行於德主界面線程點擊處理呼叫SetOnClick()

SetOnClick();置於new thread()run()中。

+0

對不起......你是對的...... LogCat顯示System.err android.os.NetwoekOnMainThreadException ...... –

0

找到另一種方式要解決這個

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

中的onCreate添加這個()