当前位置: 移动技术网 > 移动技术>移动开发>Android > Android编程实现TCP客户端的方法

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

2019年07月24日  | 移动技术网移动技术  | 我要评论

本文实例讲述了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程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网