How to implement TCP client with Android programming _android

Source: Internet
Author: User

The example in this article describes the way Android programs implement TCP clients. Share to everyone for your reference, specific as follows:

Because the project needs to implement a TCP client side, on the internet to find a lot of examples are basically blocking way to complete;

My implementation example: implemented by activity and sever, create a thread in sever to listen for accepted data. Receive data and send it to activity by radio;

Server side I did not go to implementation, you can download the TCP Socket debugging tool v2.2; Create a 9005 port; client: Access IP is 10.0.2.2

Anettest.java:

/** * Copyright 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 {/** * connects service and Activity */public STA via serviceconnection inner class implementation
   Tic final String TAG = "Anettest";
   Private static Final Boolean DEBUG = true;//false private String msg = "";
   Private Updatereceiver Mreceiver;
   Private context Mcontext;
   Private ReceiveMessage mreceivemessage; Implements a broadcastreceiver that receives the specified 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 Onservic
           econnected (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 the activity is a.
     * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
     Setcontentview (R.layout.main); Instantiate a customBroadcastreceiver mreceiver = new Updatereceiver ();
     Intentfilter filter = new Intentfilter ();
     Assigns an action to the Broadcastreceiver to receive the same action broadcast filter.addaction ("Com.archfree.demo.msg"); Registers the broadcastreceiver programmatically. The example of the configuration registration Broadcastreceiver See//Androidmanifest.xml File///general registration at OnStart, cancel registration at OnStop this.registerrece
     Iver (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 (Vie
         W 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 and Local Service interaction requires the use of the bind and Unbind methods */} @Override protected void OnDestroy () {//TODO Auto
     -generated method Stub Super.ondestroy ();
     Unbindservice (serviceconnection);
   Unregisterreceiver (Mreceiver);

 }
}

Receivemessage.java Reference network resources, modifying;

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 stubs//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 method, Localbinder class, Mbinder interface three items for the service binding, click the Send Message button to trigger the binding and through intent the activity in the EditText
The value * is routed to the server to send/public IBinder onbind (Intent Intent) {System.out.println ("-----onbind---------");
Message = Intent.getstringextra ("Chatmessage");
  if (message.length () > 0) {//Sendmessagetoserver (message);//} return Mbinder;
    The public class Localbinder extends Binder {receivemessage GetService () {return receivemessage.this;
  } private Final IBinder Mbinder = new Localbinder ();
      Used to link server-side 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 ();
    }//Disconnect the server-side link public void Disconnecttoserver () {try {client.close ();
    catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
    //Start the server-side listener thread, receive messages from the server side public void Startserverlistener () {Serverlistener a = new Serverlistener ();
  A.start ();
    ///Send message to server side 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.F
    Lag_one_shot);
    Msg.setlatesteventinfo (this, ' message ', ' message: ' + TAB, contentintent);
  Barmanager.notify (0, msg); ///Send broadcast message private void Sendmsg (String msg) {//Specify the broadcast target action (note: Receiver that specifies this action will receive this broadcast) Intent Inten
    t = new Intent ("com.archfree.demo.msg");
    The parameters to be passed Intent.putextra ("msg", MSG);
  Send broadcast this.sendbroadcast (intent);
    Private class Serverlistener extends Thread {//private Bytebuffer buf = bytebuffer.allocate (1024); PublIC void Run () {try {//wireless loop, listener server, update the UI while (true) of the activity {Bytebuffer B if there is an empty message delivery
          UF = 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);
      The 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>

For more information on Android-related content readers can view the site topics: "The Android Communication method Summary", "Android Debugging techniques and common problem solving method summary", "Android Development introduction and Advanced Course", "Android Multimedia operation tips Summary (audio, Video, audio, etc.), "Summary of Android Basic components usage", "Android View Overview", "Android Layout layout skills Summary" and "Android Control usage Summary"

I hope this article will help you with the Android program.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.