The method by which the client of Android programming communicates with the server via socket _android

Source: Internet
Author: User
Tags getmessage readline

This article is an example of how the client of Android programming communicates with the server via a socket. Share to everyone for your reference, specific as follows:

The following is a demo,android client communicates with the server through a socket.

Since Android can completely use java.io.* and java.net.* packages, the logical part is virtually indistinguishable from J2SE. Just the UI code is different.

The Android client communicates with the server through a socket with 5 steps:

(1) The socket is instantiated via IP address and port, and the connection server is requested;

Copy Code code as follows:
Socket = new Socket ("10.14.114.127", 54321); ip:10.14.114.127, Port 54321

(2) Get the socket stream to read and write, and wrap the stream into Bufferwriter or printwriter
Copy Code code as follows:
PrintWriter out = new PrintWriter (new BufferedWriter (New OutputStreamWriter (Socket.getoutputstream)), true);

Here are three classes: Socket.getoutputstream get socket output byte throttling, OutputStreamWriter is a stream of bytes to the character streams conversion bridge, Bufferwriter is the character streams, and then packaged into PrintWriter.

(3) Read and write to the socket

Copy Code code as follows:
OUT.PRINTLN (message);

(4) Close the open stream
Copy Code code as follows:
Out.close ();

The complete engineering code is as follows:

Package com.yarin.android.Examples_08_04; 
Import Java.io.BufferedReader; 
Import Java.io.BufferedWriter; 
Import Java.io.InputStreamReader; 
Import Java.io.OutputStreamWriter; 
Import Java.io.PrintWriter; 
Import Java.net.Socket; 
Import android.app.Activity; 
Import Android.os.Bundle; 
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 Activity01 extends activity {Private final String Debug_tag = "Activity01"; 
  Private TextView Mtextview = null; 
  Private EditText medittext = null; 
  Private Button Mbutton = null; /** called the activity is a. 
    * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.main); 
    Mbutton = (Button) Findviewbyid (R.ID.BUTTON01); Mtextview = (TextView) Findviewbyid (r.id.textview01); 
    Medittext = (edittext) Findviewbyid (r.id.edittext01); Login Mbutton.setonclicklistener (new Onclicklistener () {public void OnClick (View v) {SOC 
        KET socket = NULL;  
        String message = Medittext.gettext (). toString () + "/r/n";  
          try {//Create socket//socket = new Socket ("192.168.1.110", 54321); Socket = new Socket ("10.14.114.127", 54321); ip:10.14.114.127, Port 54321//Send message to server printwriter out = new PrintWriter (New BufferedWriter    
          Putstreamwriter (Socket.getoutputstream ()), true);  
          OUT.PRINTLN (message);  
          Receive messages from the server BufferedReader br = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));  
          String msg = Br.readline (); 
          if (msg!= null) {Mtextview.settext (msg); 
          else {mtextview.settext ("Data Error!"); }//OffClosed flow out.close (); 
          Br.close ();  
        Close socket Socket.close ();  
        catch (Exception e) {//Todo:handle Exception log.e (Debug_tag, e.tostring ()); 
  } 
      } 
    });

 } 
}

Layout file Main.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
"http://schemas.android.com/apk/" Res/android " 
  android:orientation=" vertical " 
  android:layout_width=" fill_parent " 
  android:layout_" height= "Fill_parent" 
  > 
  <textview  
  android:id= "@+id/textview01" android:layout_width= "  
  fill _parent "  
  android:layout_height=" wrap_content "  
  android:text=" shows the information received from the server " 
  /> 
  < EditText  
  android:id= "@+id/edittext01"  
  android:text= "Enter the content to send"  
  android:layout_width= "fill_parent "  
  android:layout_height=" wrap_content "> 
  </EditText> 
  <button  
  android:id=" @+id/ Button01 " 
  android:layout_width=" fill_parent " 
  android:layout_height=" wrap_content " 
  android:text=" "Send" 
  />  
</LinearLayout>

Androidmanifest.xml files are as follows

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android= 
"http://schemas.android.com/apk/res/" Android " 
   package=" com.yarin.android.Examples_08_04 " 
   android:versioncode=" 1 " 
   android:versionname=" 1.0 "> 
  <application android:icon=" @drawable/icon "android:label=" @string/app_name ">
    <activity Android:name= ". Activity01 " 
         android:label=" @string/app_name "> 
      <intent-filter> 
        <action android:name=" Android.intent.action.MAIN "/> 
        <category android:name=" Android.intent.category.LAUNCHER "/>" 
      </intent-filter> 
    </activity> 
  </application> 
  <uses-permission android:name= " Android.permission.INTERNET "></uses-permission> 
  <uses-sdk android:minsdkversion=" 5 "/> 
</manifest>

And of course, there's the server-side code.

Package com.yarin.android.Examples_08_04; 
Import Java.io.BufferedReader; 
Import Java.io.BufferedWriter; 
Import Java.io.InputStreamReader; 
Import Java.io.OutputStreamWriter; 
Import Java.io.PrintWriter; 
Import Java.net.ServerSocket; 
Import Java.net.Socket; public class Server implements Runnable {public void run () {try {//Create ServerSocket Server 
      Socket ServerSocket = new ServerSocket (54321); 
        while (true) {//Accept client request Socket client = Serversocket.accept (); 
        System.out.println ("accept"); try {//Receive client message BufferedReader in = new BufferedReader (New InputStreamReader Client.getinpu 
          Tstream ())); 
          String str = in.readline ();  
          System.out.println ("read:" + str); Send a message to the server printwriter out = new PrintWriter (new BufferedWriter OutputStreamWriter (client.getoutputstream    
          ()), true);  
          OUT.PRINTLN ("Server Message");Close flow out.close (); 
        In.close (); 
          catch (Exception e) {System.out.println (E.getmessage ()); 
        E.printstacktrace (); 
          Finally {//close client.close (); 
        System.out.println ("close"); 
    A catch (Exception e) {System.out.println (E.getmessage ()); }//main function, turn on server public static void main (String a[]) {Thread desktopserverthread = new Thread (New serv 
    ER ()); 
  Desktopserverthread.start ();

 } 
}

Open the server code first

Java Server can

Then start the Android emulator. Run results

This is the Android client. Enter 12345, click Send:

This is the message received from the server side

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

Related Article

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.