国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 系統(tǒng) > Android > 正文

Android編程實(shí)現(xiàn)TCP客戶端的方法

2019-12-12 06:39:37
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

本文實(shí)例講述了Android編程實(shí)現(xiàn)TCP客戶端的方法。分享給大家供大家參考,具體如下:

因?yàn)轫?xiàng)目上需要實(shí)現(xiàn)一個(gè)TCP Client 端;在網(wǎng)上找好多例子基本上都是阻塞方式完成;

我的實(shí)現(xiàn)例子:由Activity 及sever 來(lái)實(shí)現(xiàn),在sever 創(chuàng)建一個(gè)線程來(lái)監(jiān)聽(tīng)接受數(shù)據(jù)。收到數(shù)據(jù),通過(guò)廣播發(fā)送給Activity;

服務(wù)端我沒(méi)有去實(shí)現(xiàn),你可以下載TCP Socket 調(diào)試工具v2.2;創(chuàng)建個(gè)9005端口;客戶端:訪問(wèn)的IP為10.0.2.2

AnetTest.java:

/*** Copyright 2010 archfree**/package com.archfree.demo;import android.app.Activity;import android.content.BroadcastReceiver;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;public class AnetTest extends Activity {   /**   * 通過(guò)ServiceConnection的內(nèi)部類實(shí)現(xiàn)來(lái)連接Service和Activity   *   */   public static final String TAG = "AnetTest";   private static final boolean DEBUG = true;// false   private String msg = "";   private UpdateReceiver mReceiver;   private Context mContext;   private ReceiveMessage mReceiveMessage;   // 實(shí)現(xiàn)一個(gè) BroadcastReceiver,用于接收指定的 Broadcast   public class UpdateReceiver extends BroadcastReceiver {     @Override     public void onReceive(Context context, Intent intent) {       if (DEBUG)         Log.d(TAG, "onReceive: " + intent);       msg = intent.getStringExtra("msg");       System.out.println("recv:" + msg);       // System.out.println();       ((EditText) findViewById(R.id.tv_recv)).append(msg + "/n");     }   }   private ServiceConnection serviceConnection = new ServiceConnection() {     @Override     public void onServiceConnected(ComponentName name, IBinder service) {       mReceiveMessage = ((ReceiveMessage.LocalBinder) service)           .getService();       if (DEBUG)         Log.d(TAG, "on serivce connected");     }     @Override     public void onServiceDisconnected(ComponentName name) {       mReceiveMessage = null;     }   };   /** Called when the activity is first created. */   @Override   public void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.main);     // 實(shí)例化自定義的 BroadcastReceiver     mReceiver = new UpdateReceiver();     IntentFilter filter = new IntentFilter();     // 為 BroadcastReceiver 指定 action ,使之用于接收同 action 的廣播     filter.addAction("com.archfree.demo.msg");     // 以編程方式注冊(cè) BroadcastReceiver 。配置方式注冊(cè) BroadcastReceiver 的例子見(jiàn)     // AndroidManifest.xml 文件     // 一般在 OnStart 時(shí)注冊(cè),在 OnStop 時(shí)取消注冊(cè)     this.registerReceiver(mReceiver, filter);     mContext = AnetTest.this;     /**     * Button bn_conn bn_send bn_bind bn_unbind     */     // Button bn_conn = (Button) findViewById(R.id.bn_conn);     Button bn_send = (Button) findViewById(R.id.bn_send);     Button bn_bind = (Button) findViewById(R.id.bn_bind);     Button bn_unbind = (Button) findViewById(R.id.bn_unbind);     EditText tv_recv = (EditText) findViewById(R.id.tv_recv);     /**     * EditText et_send     */     EditText et_send = (EditText) findViewById(R.id.et_send);     /**     * bn_send on click     */     bn_send.setOnClickListener(new OnClickListener() {       public void onClick(View arg0) {         // TODO         ((EditText) findViewById(R.id.tv_recv)).clearComposingText();         mReceiveMessage            .SendMessageToServer("0001058512250000190010900005300010001354758032278512   460029807503542       0613408000011    ");       }     });     /**     * bn_bind on click     */     bn_bind.setOnClickListener(new OnClickListener() {       public void onClick(View arg0) {         // TODO         Intent i = new Intent();         Bundle bundle = new Bundle();         bundle.putString("chatmessage",             ((EditText) findViewById(R.id.et_send)).getText()                 .toString());         i.putExtras(bundle);         System.out.println(" send onclick");         bindService(new Intent("com.archfree.demo.ReceiveMessage"),             serviceConnection, BIND_AUTO_CREATE);       }     });     /**     * bn_unbind on click     */     bn_unbind.setOnClickListener(new OnClickListener() {       public void onClick(View arg0) {         // TODO         mContext.unbindService(serviceConnection);       }     });     /**     * Activity和本地服務(wù)交互,需要使用bind和unbind方法     * */   }   @Override   protected void onDestroy() {     // TODO Auto-generated method stub     super.onDestroy();     unbindService(serviceConnection);     unregisterReceiver(mReceiver);   }}

ReceiveMessage.java 參考網(wǎng)絡(luò)資源,修改;

package com.archfree.demo;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.CharBuffer;import java.nio.channels.SocketChannel;import java.nio.charset.CharacterCodingException;import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.app.Service;import android.content.Context;import android.content.Intent;import android.os.Binder;import android.os.IBinder;public class ReceiveMessage extends Service {  // @Override  // public int onStartCommand(Intent intent, int flags, int startId) {  // // TODO Auto-generated method stub  // return super.onStartCommand(intent, flags, startId);  // }  private SocketChannel client = null;  private InetSocketAddress isa = null;  private String message = "";  public void onCreate() {    System.out.println("----- onCreate---------");    super.onCreate();    ConnectToServer();    StartServerListener();  }  public void onDestroy() {    super.onDestroy();    DisConnectToServer();  }  public void onStart(Intent intent, int startId) {    System.out.println("----- onStart---------");    super.onStart(intent, startId);  }  /*   * IBinder方法 , LocalBinder 類,mBinder接口這三項(xiàng)用于   * Activity進(jìn)行Service的綁定,點(diǎn)擊發(fā)送消息按鈕之后觸發(fā)綁定 并通過(guò)Intent將Activity中的EditText的值   * 傳送到Service中向服務(wù)器發(fā)送   */  public IBinder onBind(Intent intent) {    System.out.println("----- onBind---------");//    message = intent.getStringExtra("chatmessage");//    if (message.length() > 0) {//      SendMessageToServer(message);//    }    return mBinder;  }  public class LocalBinder extends Binder {    ReceiveMessage getService() {      return ReceiveMessage.this;    }  }  private final IBinder mBinder = new LocalBinder();  // 用于鏈接服務(wù)器端  public void ConnectToServer() {    try {      client = SocketChannel.open();      //isa = new InetSocketAddress("10.0.2.2", 9005);      isa = new InetSocketAddress("211.141.230.246", 6666);      client.connect(isa);      client.configureBlocking(false);    } catch (IOException e) {      // TODO Auto-generated catch block      e.printStackTrace();    }  }  // 斷開(kāi)與服務(wù)器端的鏈接  public void DisConnectToServer() {    try {      client.close();    } catch (IOException e) {      // TODO Auto-generated catch block      e.printStackTrace();    }  }  // 啟動(dòng)服務(wù)器端的監(jiān)聽(tīng)線程,從Server端接收消息  public void StartServerListener() {    ServerListener a = new ServerListener();    a.start();  }  // 向Server端發(fā)送消息  public void SendMessageToServer(String msg) {    System.out.println("Send:" + msg);    try {      ByteBuffer bytebuf = ByteBuffer.allocate(1024);      bytebuf = ByteBuffer.wrap(msg.getBytes("UTF-8"));      client.write(bytebuf);      bytebuf.flip();    } catch (IOException e) {      // TODO Auto-generated catch block      e.printStackTrace();      System.out.println(" SendMessageToServer IOException===");    }  }  private void shownotification(String tab) {    System.out.println("shownotification=====" + tab);    NotificationManager barmanager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);    Notification msg = new Notification(        android.R.drawable.stat_notify_chat, "A Message Coming!",        System.currentTimeMillis());    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,        new Intent(this, AnetTest.class), PendingIntent.FLAG_ONE_SHOT);    msg.setLatestEventInfo(this, "Message", "Message:" + tab, contentIntent);    barmanager.notify(0, msg);  }  // 發(fā)送廣播信息  private void sendMsg(String msg){    // 指定廣播目標(biāo)的 action (注:指定了此 action 的 receiver 會(huì)接收此廣播)    Intent intent = new Intent("com.archfree.demo.msg");    // 需要傳遞的參數(shù)    intent.putExtra("msg", msg);    // 發(fā)送廣播    this.sendBroadcast(intent);  }  private class ServerListener extends Thread {    //private  ByteBuffer buf = ByteBuffer.allocate(1024);    public void run() {      try {        // 無(wú)線循環(huán),監(jiān)聽(tīng)服務(wù)器,如果有不為空的信息送達(dá),則更新Activity的UI        while (true) {          ByteBuffer buf = ByteBuffer.allocate(1024);          //buf.clear();          client.read(buf);          buf.flip();          Charset charset = Charset.forName("UTF-8");          CharsetDecoder decoder = charset.newDecoder();          CharBuffer charBuffer;          charBuffer = decoder.decode(buf);          String result = charBuffer.toString();          if (result.length() > 0)          {// recvData(result);            sendMsg(result);            //System.out.println("+++++="+result);            //shownotification(result);          }          // System.out.println("++++++++++++++++++="+result);        }      } catch (CharacterCodingException e) {        // TODO Auto-generated catch block        e.printStackTrace();      } catch (IOException e) {        // TODO Auto-generated catch block        e.printStackTrace();      }    }  }}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"  package="com.archfree.demo" android:versionCode="1"  android:versionName="1.0">  <application android:icon="@drawable/icon" android:label="@string/app_name">    <activity android:name=".AnetTest" android:label="@string/app_name">      <intent-filter>        <action android:name="android.intent.action.MAIN" />        <category android:name="android.intent.category.LAUNCHER" />      </intent-filter>    </activity>

更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android通信方式總結(jié)》、《Android調(diào)試技巧與常見(jiàn)問(wèn)題解決方法匯總》、《Android開(kāi)發(fā)入門(mén)與進(jìn)階教程》、《Android多媒體操作技巧匯總(音頻,視頻,錄音等)》、《Android基本組件用法總結(jié)》、《Android視圖View技巧總結(jié)》、《Android布局layout技巧總結(jié)》及《Android控件用法總結(jié)

希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 博白县| 仙游县| 渝北区| 疏附县| 汽车| 东台市| 禄丰县| 无锡市| 开化县| 长治县| 息烽县| 驻马店市| 兰溪市| 贞丰县| 察雅县| 如皋市| 乌拉特后旗| 蓬莱市| 永兴县| 澄城县| 辉南县| 三都| 花莲市| 精河县| 怀仁县| 天柱县| 大石桥市| 花垣县| 诏安县| 西盟| 竹山县| 安多县| 云龙县| 禄劝| 兴化市| 邹城市| 邯郸市| 常山县| 内丘县| 麦盖提县| 东阳市|