Android

关注公众号 jb51net

关闭
首页 > 软件编程 > Android > Android TCP客户端

Android编程实现TCP客户端的方法

作者:sdvch

这篇文章主要介绍了Android编程实现TCP客户端的方法,结合实例形式分析了Android实现TCP客户端的原理及数据通信的相关技巧,需要的朋友可以参考下

本文实例讲述了Android编程实现TCP客户端的方法。分享给大家供大家参考,具体如下:

因为项目上需要实现一个TCP Client 端;在网上找好多例子基本上都是阻塞方式完成;

我的实现例子:由Activity 及sever 来实现,在sever 创建一个线程来监听接受数据。收到数据,通过广播发送给Activity;

服务端我没有去实现,你可以下载TCP Socket 调试工具v2.2;创建个9005端口;客户端:访问的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 {
   /**
   * 通过ServiceConnection的内部类实现来连接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;
   // 实现一个 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);
     // 实例化自定义的 BroadcastReceiver
     mReceiver = new UpdateReceiver();
     IntentFilter filter = new IntentFilter();
     // 为 BroadcastReceiver 指定 action ,使之用于接收同 action 的广播
     filter.addAction("com.archfree.demo.msg");
     // 以编程方式注册 BroadcastReceiver 。配置方式注册 BroadcastReceiver 的例子见
     // AndroidManifest.xml 文件
     // 一般在 OnStart 时注册,在 OnStop 时取消注册
     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和本地服务交互,需要使用bind和unbind方法
     * */
   }
   @Override
   protected void onDestroy() {
     // TODO Auto-generated method stub
     super.onDestroy();
     unbindService(serviceConnection);
     unregisterReceiver(mReceiver);
   }
}

ReceiveMessage.java 参考网络资源,修改;

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接口这三项用于
   * Activity进行Service的绑定,点击发送消息按钮之后触发绑定 并通过Intent将Activity中的EditText的值
   * 传送到Service中向服务器发送
   */
  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();
  // 用于链接服务器端
  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();
    }
  }
  // 断开与服务器端的链接
  public void DisConnectToServer() {
    try {
      client.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  // 启动服务器端的监听线程,从Server端接收消息
  public void StartServerListener() {
    ServerListener a = new ServerListener();
    a.start();
  }
  // 向Server端发送消息
  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);
  }
  // 发送广播信息
  private void sendMsg(String msg){
    // 指定广播目标的 action (注:指定了此 action 的 receiver 会接收此广播)
    Intent intent = new Intent("com.archfree.demo.msg");
    // 需要传递的参数
    intent.putExtra("msg", msg);
    // 发送广播
    this.sendBroadcast(intent);
  }
  private class ServerListener extends Thread {
    //private  ByteBuffer buf = ByteBuffer.allocate(1024);
    public void run() {
      try {
        // 无线循环,监听服务器,如果有不为空的信息送达,则更新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>

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android通信方式总结》、《Android调试技巧与常见问题解决方法汇总》、《Android开发入门与进阶教程》、《Android多媒体操作技巧汇总(音频,视频,录音等)》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结

希望本文所述对大家Android程序设计有所帮助。

您可能感兴趣的文章:
阅读全文