Application analysis of socket in Android _android

Source: Internet
Author: User
Tags gettext readline stub

The application of socket in Android is analyzed in this paper. Share to everyone for your reference, specific as follows:

The common network programming provided by Android includes socket communications for TCP/IP protocols. A socket is a cross-platform programming way to communicate between heterogeneous languages.

The development principle of socket program is to implement server side and client.

Server, using ServerSocket to listen to the specified port, the port can be arbitrarily specified (because the port under 1024 is usually reserved port, in some operating systems are not free to use, so it is recommended to use a port greater than 1024), waiting for customer connection request, after the client connected, the session generated , and close the connection after the session completes.

Client, use the socket to issue a connection request to a port on one of the servers on the network, open the session once the connection is successful, and close the socket after the session completes. The client does not need to specify an open port, typically temporarily, dynamically allocating more than 1024 ports.

Here is an example of implementing a socket:

Server-side code:

Package com.socket;
Import Java.io.BufferedReader;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import Java.io.PrintWriter;
Import Java.net.ServerSocket;
Import Java.net.Socket;
  /** * COM Server */public class Main {private int serverport = 9999;
  Private ServerSocket serversocket = null;
  Private OutputStream outputstream = null;
  Private InputStream InputStream = null;
  private PrintWriter printwinter = null;
  Private socket socket = NULL;
  Private BufferedReader reader = null;
      Public Main () {try{serversocket = new ServerSocket (serverport); SYSTEM.OUT.PRINTLN ("Service startup ...")
      ");
      Socket = Serversocket.accept ();
    System.out.println ("Customer is connected");
    }catch (Exception ex) {ex.printstacktrace ();
      } try{outputstream= Socket.getoutputstream ();
      InputStream = Socket.getinputstream ();
      Printwinter = new PrintWriter (outputstream,true); reader = new BufferedReader (New InputStreamReader(InputStream));
      BufferedReader in = new BufferedReader (new InputStreamReader (system.in));
        while (true) {a String message = Reader.readline ();
        SYSTEM.OUT.PRINTLN ("Client:" +message); if (Message.equals ("Bye") | |
        Message.equals ("Bye")) {break;
        } message = In.readline ();
      PRINTWINTER.PRINTLN (message);
      } outputstream.close ();
      Inputstream.close ();
      Socket.close ();
      Serversocket.close ();
    System.out.print ("Client is disconnected");
    }catch (Exception e) {e.printstacktrace ();
  }finally{}} public static void Main (string[] args) {new Main ();

 }
}

Customer Service-side code:

Package com.
aina.android;
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.app.AlertDialog;
Import Android.content.DialogInterface;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.util.Log;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.EditText;
Import Android.widget.TextView; The public class Test extends activity implements Runnable {/** called the ' when ' is the ' activity ' is a-created
W tv_msg = null;
Private EditText ed_msg = null;
Private Button btn_send = null;
Private Button btn_login = null;
private static final String HOST = "192.168.0.132";
private static final int PORT = 9999;
Private socket socket = NULL;
Private BufferedReader in = null;
Private printwriter out = null;
Private String content = ""; @Override PubLIC void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
 Setcontentview (R.layout.main);
 Tv_msg = (TextView) This.findviewbyid (R.id.textview);
 Ed_msg = (edittext) This.findviewbyid (r.id.edittext01);
 Btn_login = (Button) This.findviewbyid (R.ID.BUTTON01);
 Btn_send = (Button) This.findviewbyid (R.ID.BUTTON02);
  try {socket = new socket (HOST, PORT);
  in = new BufferedReader (new InputStreamReader (socket. getInputStream ()));
 out = new PrintWriter (new BufferedWriter (New OutputStreamWriter (Socket.getoutputstream ())), true);
  catch (Exception ex) {ex.printstacktrace ();
 ShowDialog ("Landing anomaly:" + ex.getmessage ()); Btn_send.setonclicklistener (New Button.onclicklistener () {public void OnClick (View v) {//TODO auto-generated met
  Hod stub String msg = Ed_msg.gettext (). toString ();
   if (socket.isconnected ()) {if (!socket.isoutputshutdown ()) {out.println (msg);
 }
  }
  }
 });
New Thread (This). Start (); public void ShowDialog (Stringmsg) {New Alertdialog.builder (this). Settitle ("hint"). Setmessage (msg). Setpositivebutton ("OK", new Dialoginterface.onclicklistener () {public void OnClick (Dialoginterface dialog, int which) {//TODO auto-generated
Method stub}}). Show (); public void Run () {try {() {if (true) {if (socket.isconnected ()) {if (!socket.isinputshutdown ()) {if (Conten
    t = In.readline ())!= null) {LOG.I ("TAG", "+ +" +content);
    Content + = "\ n";
   Mhandler.sendmessage (Mhandler.obtainmessage ());
 }else{}}} catch (Exception ex) {ex.printstacktrace ();
  Handler Mhandler = new Handler () {public void Handlemessage (message msg) {super.handlemessage (msg);
  LOG.I ("TAG", "--" +msg);
 Tv_msg.settext (Tv_msg.gettext (). toString () + content);
}
};

 }

XML File layout:

<?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/textview "android:singleline=" false "
 Android:layout_width = "Fill_parent"
 android:layout_height= "wrap_content"/>
<edittext android:hint= "content" android:id= "@+id/edittext01"
 android:layout_width= "fill_parent"
 android:layout_height= "wrap_content" >
</EditText>
<button android:text= "Login" android:id= "@+id/button01"
 android:layout_width= " Fill_parent "
 android:layout_height=" wrap_content ">
</Button>
<button android:text=" Send "android:id=" @+id/button02 "
 android:layout_width=" fill_parent "
 android:layout_height=" Wrap_ Content ">
</Button>
</LinearLayout>

Start the server side first, then run the client program.

Attention:

(i) Even if the server-side and the client are running on a single machine, the IP address cannot be used: 127.0.0.1, otherwise, the program will receive an error that rejects the connection.

(b) The client and server side is best not built in a project, preferably to build the project separately, and then start the server side and the client, otherwise it will report Error:shouldnotreachhere () error. This is because the Android program is not the main method for the program's entry.

Operation Effect:

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.

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.