Android實現(xiàn)TCP客戶端支持讀寫操作

本篇我們便來學習如何通過socket讀寫TCP.

創(chuàng)新互聯(lián)公司是一家集成都網(wǎng)站設計、網(wǎng)站制作、網(wǎng)站頁面設計、網(wǎng)站優(yōu)化SEO優(yōu)化為一體的專業(yè)網(wǎng)絡公司,已為成都等多地近百家企業(yè)提供網(wǎng)站建設服務。追求良好的瀏覽體驗,以探求精品塑造與理念升華,設計最適合用戶的網(wǎng)站頁面。 合作只是第一步,服務才是根本,我們始終堅持講誠信,負責任的原則,為您進行細心、貼心、認真的服務,與眾多客戶在蓬勃發(fā)展的市場環(huán)境中,互促共生。

需要注意的是socket必須寫在子線程中,不能在ui主線程中直接使用,所以我們這里創(chuàng)建了兩個class:

MainActivity(主界面)、TcpThread(獲取socket接收的數(shù)據(jù))

由于代碼有注釋了,所以就不解釋了.

1.gif效果如下

Android實現(xiàn)TCP客戶端支持讀寫操作

2.activity_main.xml如下所示:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context=".MainActivity" >
 <EditText 
  android:id="@+id/et_text"
  android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_alignParentTop="true"
  android:hint="請?zhí)钊胍l(fā)送的內(nèi)容"
  />
  <Button 
  android:id="@+id/btn_send"
  android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignParentRight="true"
   android:layout_below="@+id/et_text"
  android:text="發(fā)送"
  />
  <TextView 
   android:id="@+id/tv_recv"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_below="@+id/btn_send"
   android:minLines="20"
   android:hint="接收的內(nèi)容"
   />
</RelativeLayout>

3.MainActivity.java如下所示

package com.example.tcpdemo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
 TcpThread mt;
 TextView tv_recv;
 EditText et_text;  //要發(fā)送的內(nèi)容
 Button btn_send;
 //定義一個handler
 public Handler mHandler = new Handler() {
  public void handleMessage(Message msg) {
   //打印服務器端發(fā)來的消息
   System.out.println("read:"+msg.obj.toString());
   tv_recv.append(msg.obj.toString()+"\r\n");
  };
 };
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  tv_recv = (TextView)findViewById(R.id.tv_recv);
  et_text = (EditText)findViewById(R.id.et_text);
  mt = new TcpThread();
  mt.setHandler(mHandler); //設置handler
  mt.setIp("10.10.10.104"); //設置服務器地址
  mt.start();     //啟動線程
  btn_send = (Button)findViewById(R.id.btn_send);
  btn_send.setOnClickListener(new OnClickListener() {
   //向服務器端發(fā)送數(shù)據(jù)
   public void onClick(View v) {
    if(!mt.write(et_text.getText().toString()))
    {
     Toast.makeText(getApplicationContext(), "發(fā)送失敗", Toast.LENGTH_SHORT).show();
    }
   }
  });
 }
}

4.TcpThread.java如下所示

package com.example.tcpdemo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Handler;
import android.os.Message;
public class TcpThread extends Thread {
  
  Handler mHandler=null; 
  Socket socket = null;
  String ip = null;
  OutputStream outputStream = null;  //輸出流
  InputStream inputStream=null;   //接收流
  //獲取另一個線程的Handler
  public void setHandler( Handler handler){
   mHandler = handler;
  }
  //設置服務器IP
  public void setIp(String ip){
   this.ip = ip;
  }
  public void run(){
   try {
     socket = new Socket(ip, 8080);  //訪問指定的ip地址:8080
    } catch (UnknownHostException e) { 
     e.printStackTrace();
    } catch (IOException e) { 
     e.printStackTrace();
    }
   
   //獲取輸出流
   try {
    outputStream = socket.getOutputStream();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } 
   try{
    while (true)   //讀取服務器端發(fā)送來的數(shù)據(jù)
    {
     final byte[] buffer = new byte[1024];//創(chuàng)建接收緩沖區(qū)
     inputStream = socket.getInputStream();
     final int len = inputStream.read(buffer);//數(shù)據(jù)讀出來,并且返回數(shù)據(jù)的長度
     if(len>0)
     {
       Message msg = mHandler.obtainMessage(); 
       //設置發(fā)送的內(nèi)容
       msg.obj = new String(buffer,0,len); 
       mHandler.sendMessage(msg); 
     }
    }
   }
   catch (IOException e) {
   }
  }
  //向服務器端寫入數(shù)據(jù)
  public boolean write(String text){
   boolean ret = true;
   try {
    outputStream.write(text.toString().getBytes());
   } catch (IOException e) { 
    ret = false;
    e.printStackTrace();
   }
   return ret;
  }
}

總結(jié)

以上所述是小編給大家介紹的Android實現(xiàn)TCP客戶端支持讀寫操作,希望對大家有所幫助!

網(wǎng)頁標題:Android實現(xiàn)TCP客戶端支持讀寫操作
本文URL:http://www.muchs.cn/article16/jiopdg.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供App設計、網(wǎng)站策劃、服務器托管企業(yè)網(wǎng)站制作、動態(tài)網(wǎng)站響應式網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都app開發(fā)公司