android TCP 用戶端(僅接收資料)

來源:互聯網
上載者:User

標籤:android   blog   class   c   code   java   

配合log4net使用,用來接收調試資訊。因此,此用戶端只管通過TCP接收字串資料,然後顯示在介面上。

接收TCP資料

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 try {     Socket s = new Socket("192.168.1.5", 8240);     InputStream inputStream = s.getInputStream();     DataInputStream input = new DataInputStream(inputStream);     byte[] b = new byte[10000];     while(true)     {         int length = input.read(b);         String Msg = new String(b, 0, length, "gb2312");         Log.v("data",Msg);     } }catch(Exception ex) {     ex.printStackTrace(); }

開線程執行接收操作  

 但是,如果接收代碼直接放UI按鈕處理事件中,將直接引發NetworkOnMainThreadException,這是因為不能在主線程中執行Socket操作。這裡使用AsyncTask開另一個線程執行socket操作。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // Activity按鈕事件中 GetLogTask task = new GetLogTask(); task.execute(null); // Activity類中嵌套類 public class GetLogTask extends AsyncTask<Void,Void,String> {     @Override     protected String doInBackground(Void...param){             try {             Socket s = new Socket("192.168.1.5", 8240);             InputStream inputStream = s.getInputStream();             DataInputStream input = new DataInputStream(inputStream);             byte[] b = new byte[10000];             while(true)             {                 int length = input.read(b);                 String Msg = new String(b, 0, length, "gb2312");                 Log.v("data",Msg);             }                       }catch(Exception ex)         {             ex.printStackTrace();         }         return "";     } }

  AsyncTask與介面線程通訊

1、介面需要啟動和暫停TCP接收操作。
介面線程使用AsyncTask.cancel()通知接收線程結束接收操作。
接收線程在doInBackground中調用isCancelled()來檢查是否出現結束接收要求。

 

2、AsyncTask接收到資料之後,傳遞給介面顯示。

接收線程使用Handler將資料傳遞給介面
使用Handler的話,資料作為“訊息”傳遞給介面處理。
Handler包括了處理訊息功能和發布訊息功能。在這裡,處理訊息就是在介面上顯示log文本,介面線程來幹。發布訊息就是將log文本作為參數,調用postmessage功能,接收線程來幹。

主線程中的處理訊息

?
1 2 3 4 5 6 Handler handler = new Handler(){     @Override     public void handleMessage(Message msg){         text.setText(text.getText().toString()+(String)msg.obj);     } };

接收線程中的發布訊息

?
1 2 3 Message msg = new Message(); msg.obj = msgstring; (MainActivity.this).handler.postMessage();

以上就構成了一個簡單,但可用的TCP方式的log接收端。拿個360wifi或者小米wifi,就可以使用手機接收pc應用程式發出來的log了。

很久沒有登陸自己的帳號了,還好自己的帳號還在,慶幸之餘,發一篇今天的隨筆,感謝園子一直保留著這份記憶。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.