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
- <span style="font-family:comic Sans ms;font-size:18px;" >import java.io.BufferedWriter;
- Import java.io.IOException;
- Import Java.io.OutputStreamWriter;
- Import Java.net.ServerSocket;
- Import Java.net.Socket;
- Public class Main {
- private static final int PORT = 9999;
- public static void Main (string[] args) {
- try {
- //Instantiate server sockets set port number 9999
- ServerSocket Server = new ServerSocket (PORT);
- While (true) {
- Socket socket = server.accept ();
- //Get output stream
- BufferedWriter writer = New BufferedWriter (
- New OutputStreamWriter (Socket.getoutputstream ()));
- //write String
- Writer.write ("This is a greeting from the server: Hello Ward! ");
- Writer.flush ();
- Writer.close ();
- }
- } catch (IOException e) {
- //TODO auto-generated catch block
- E.printstacktrace ();
- }
- }
- }
- </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
- <span style="font-family:comic Sans ms;font-size:18px;" > PackageCom.example.socketdemo;
- Import Java.io.BufferedReader;
- Import java.io.IOException;
- Import Java.io.InputStreamReader;
- Import Java.net.Socket;
- Import java.net.UnknownHostException;
- Import Android.annotation.SuppressLint;
- Import android.app.Activity;
- Import Android.os.Bundle;
- Import Android.os.Handler;
- Import Android.os.Message;
- Import Android.util.Log;
- Import Android.view.View;
- Import Android.view.View.OnClickListener;
- Import Android.widget.Button;
- Import Android.widget.TextView;
- @SuppressLint ("Handlerleak")
- Public class Socketdemo extends Activity {
- /** Called when the activity is first created. * /
- private Button btn_receive;
- private TextView txt;
- private String Line;
- private static final String HOST = "192.168.1.101";
- private static final int PORT = 9999;
- @Override
- public void OnCreate (Bundle savedinstancestate) {
- super.oncreate (savedinstancestate);
- Setcontentview (R.layout.activity_main);
- Initcontrol ();
- }
- private void Initcontrol () {
- Btn_receive = (Button) Findviewbyid (r.id.btn_receive);
- txt = (TextView) Findviewbyid (r.id.txt);
- Btn_receive.setonclicklistener (new Receiverlistener ());
- }
- @SuppressLint ("Handlerleak")
- class Receiverlistener implements Onclicklistener {
- @Override
- public void OnClick (View v) {
- //TODO auto-generated method stub
- New Thread () {
- @Override
- public Void Run () {
- //Send an empty message to handler after execution is complete
- try {
- //Instantiate socket
- Socket socket = new socket (HOST, PORT);
- //Get input stream
- BufferedReader br = new BufferedReader (
- New InputStreamReader (Socket.getinputstream ()));
- line = Br.readline ();
- Br.close ();
- } catch (Unknownhostexception e) {
- //TODO auto-generated catch block
- E.printstacktrace ();
- } catch (IOException e) {
- //TODO auto-generated catch block
- E.printstacktrace ();
- }
- Handler.sendemptymessage (0);
- }
- }.start ();
- }
- }
- //Define Handler object
- private Handler Handler = new Handler () {
- @Override
- //When a message is sent out, execute the handler method
- public void Handlemessage (Message msg) {
- super.handlemessage (msg);
- //Processing UI
- Txt.settext (line);
- LOG.I ("PDA", "----->" + line);
- }
- };
- }
- </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