Android Socket Programming Learning Notes

Source: Internet
Author: User

http://blog.csdn.net/eyu8874521/article/details/8847173

Degrees Niang gives the description:
Often also referred to as a "socket," which describes the IP address and port, is a handle to a communication chain. Hosts on the internet typically run multiple service software, while providing several services. Each service opens a socket and binds to a port, and the different ports correspond to different services.

The two programs on the network realize the exchange of data through a two-way communication connection, one end of this bidirectional link is called a socket. Sockets are typically used to connect clients and service parties. Sockets are a very popular programming interface for the TCP/IP protocol, and a socket is uniquely determined by an IP address and a port number.

In Java, the sockets and ServerSocket class libraries are located in the Java. NET package. ServerSocket is used for server-side, socket is used when establishing network connection. When the connection succeeds, a socket instance is generated at both ends of the application, manipulating the instance to complete the required session.

Below is a very simple example of a client and server connection that demonstrates the most basic Android socket communication:

Server-side code that listens for client requests on a server-specific port 9999, executes as soon as it is requested, and then continues to listen. Using the Accept () block function, the method is called and waits for the client's request until a request is connected to the same port, and accept () returns a socket corresponding to the client. In this example, it is very simple, the server is constantly listening, once the request to output a piece of information:

[Java]View Plaincopy
  1. <span style="font-family:comic Sans ms;font-size:18px;"  >import java.io.BufferedWriter;
  2. Import java.io.IOException;
  3. Import Java.io.OutputStreamWriter;
  4. Import Java.net.ServerSocket;
  5. Import Java.net.Socket;
  6. Public class Main {
  7. private static final int PORT = 9999;
  8. public static void Main (string[] args) {
  9. try {
  10. //Instantiate server sockets set port number 9999
  11. ServerSocket Server = new ServerSocket (PORT);
  12. While (true) {
  13. Socket socket = server.accept ();
  14. //Get output stream
  15. BufferedWriter writer = New BufferedWriter (
  16. New OutputStreamWriter (Socket.getoutputstream ()));
  17. //write String
  18. Writer.write ("This is a greeting from the server: Hello Ward!  ");
  19. Writer.flush ();
  20. Writer.close ();
  21. }
  22. } catch (IOException e) {
  23. //TODO auto-generated catch block
  24. E.printstacktrace ();
  25. }
  26. }
  27. }
  28. </span>


The following is the content of the Android client, the interface has a button, click on the server to request the development of the port, and then display the contents of the server, It is noteworthy that in android4.0 above system, is not allowed in the main thread to perform network-related requests, or will error: Networkonmainthreadexception, so in this example, a new thread to initialize the contents of the socket:

[Java]View Plaincopy
  1. <span style="font-family:comic Sans ms;font-size:18px;"  > PackageCom.example.socketdemo;
  2. Import Java.io.BufferedReader;
  3. Import java.io.IOException;
  4. Import Java.io.InputStreamReader;
  5. Import Java.net.Socket;
  6. Import java.net.UnknownHostException;
  7. Import Android.annotation.SuppressLint;
  8. Import android.app.Activity;
  9. Import Android.os.Bundle;
  10. Import Android.os.Handler;
  11. Import Android.os.Message;
  12. Import Android.util.Log;
  13. Import Android.view.View;
  14. Import Android.view.View.OnClickListener;
  15. Import Android.widget.Button;
  16. Import Android.widget.TextView;
  17. @SuppressLint ("Handlerleak")
  18. Public class Socketdemo extends Activity {
  19. /** Called when the activity is first created. * /
  20. private Button btn_receive;
  21. private TextView txt;
  22. private String Line;
  23. private static final String HOST = "192.168.1.101";
  24. private static final int PORT = 9999;
  25. @Override
  26. public void OnCreate (Bundle savedinstancestate) {
  27. super.oncreate (savedinstancestate);
  28. Setcontentview (R.layout.activity_main);
  29. Initcontrol ();
  30. }
  31. private void Initcontrol () {
  32. Btn_receive = (Button) Findviewbyid (r.id.btn_receive);
  33. txt = (TextView) Findviewbyid (r.id.txt);
  34. Btn_receive.setonclicklistener (new Receiverlistener ());
  35. }
  36. @SuppressLint ("Handlerleak")
  37. class Receiverlistener implements Onclicklistener {
  38. @Override
  39. public void OnClick (View v) {
  40. //TODO auto-generated method stub
  41. New Thread () {
  42. @Override
  43. public Void Run () {
  44. //Send an empty message to handler after execution is complete
  45. try {
  46. //Instantiate socket
  47. Socket socket = new socket (HOST, PORT);
  48. //Get input stream
  49. BufferedReader br = new BufferedReader (
  50. New InputStreamReader (Socket.getinputstream ()));
  51. line = Br.readline ();
  52. Br.close ();
  53. } catch (Unknownhostexception e) {
  54. //TODO auto-generated catch block
  55. E.printstacktrace ();
  56. } catch (IOException e) {
  57. //TODO auto-generated catch block
  58. E.printstacktrace ();
  59. }
  60. Handler.sendemptymessage (0);
  61. }
  62. }.start ();
  63. }
  64. }
  65. //Define Handler object
  66. private Handler Handler = new Handler () {
  67. @Override
  68. //When a message is sent out, execute the handler method
  69. public void Handlemessage (Message msg) {
  70. super.handlemessage (msg);
  71. //Processing UI
  72. Txt.settext (line);
  73. LOG.I ("PDA", "----->" + line);
  74. }
  75. };
  76. }
  77. </span>


As follows:

Also in the configuration file remember to add permissions: <uses-permission android:name= "Android.permission.INTERNET" >

When testing, start the server, then start the client, click on the button to get information on the server. This is a simple little example of an Android socket, it is easy to get a simple understanding of the socket, this note is the first to remember here!

Reference article:

Http://blog.sina.com.cn/s/blog_685790700100xjuo.html

Http://www.cnblogs.com/linzheng/archive/2011/01/23/1942328.html

Android Socket Programming Learning Notes

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.