Description provided by Du Niang:
It is also called "socket". It is used to describe the IP address and port and is a communication chain handle. Hosts on the Internet generally run multiple service software and provide several services at the same time. Each service opens a Socket and binds it to a port. Different ports correspond to different services.
Two programs on the network exchange data through a two-way communication connection. one end of this two-way link is called a Socket. Socket is usually used to connect the customer and the service provider. Socket is a very popular programming interface of TCP/IP protocol. A Socket is uniquely identified by an IP address and a port number.
In java, the Socket and ServerSocket class libraries are located in the java. net package. ServerSocket is used on the server side. Socket is used to establish a network connection. When the connection is successful, a Socket instance is generated at both ends of the application to complete the required session.
The following uses an extremely simple connection between the client and the server to demonstrate the most basic android socket communication:
The server-side code listens to client requests on the server-side specific port 9999. Once there is a request, it will be executed and then continue to listen. When you use the accept () blocking function, it waits for the client's request after the method is called until a request is sent and connected to the same port, accept () returns a Socket corresponding to the client. In this example, the server continuously listens and outputs a piece of information once there is a request:
[Java]
<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 the server socket to set port 9999
ServerSocket server = new ServerSocket (PORT );
While (true ){
Socket socket = server. accept ();
// Obtain the output stream
BufferedWriter writer = new BufferedWriter (
New OutputStreamWriter (socket. getOutputStream ()));
// Write a 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>
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 the server socket to set port 9999
ServerSocket server = new ServerSocket (PORT );
While (true ){
Socket socket = server. accept ();
// Obtain the output stream
BufferedWriter writer = new BufferedWriter (
New OutputStreamWriter (socket. getOutputStream ()));
// Write a 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 ();
}
}
}
The following content is related to the android client. A button is displayed on the interface. After you click the button, you are requested to create a port for the server and then the server content is displayed. It is worth noting that in systems above android4.0, it is not allowed to execute network-related requests in the main thread. Otherwise, the error NetworkOnMainThreadException will be reported. Therefore, in this example, we will open up a thread to initialize socket content:
[Java]
<SPAN style = "FONT-FAMILY: Comic Sans MS; FONT-SIZE: 18px"> package com. 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.
Try {
// Instantiate the Socket
Socket socket = new Socket (HOST, PORT );
// Obtain the 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 the Handler object
Private Handler handler = new Handler (){
@ Override
// Execute the Handler method when a message is sent.
Public void handleMessage (Message msg ){
Super. handleMessage (msg );
// Process the UI
Txt. setText (line );
Log. I ("PDA", "----->" + line );
}
};
}
</SPAN>
Package com. 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.
Try {
// Instantiate the Socket
Socket socket = new Socket (HOST, PORT );
// Obtain the 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 the Handler object
Private Handler handler = new Handler (){
@ Override
// Execute the Handler method when a message is sent.
Public void handleMessage (Message msg ){
Super. handleMessage (msg );
// Process the UI
Txt. setText (line );
Log. I ("PDA", "----->" + line );
}
};
}
As follows:
In addition, remember to add the permission in the configuration file: <uses-permission android: name = "android. permission. INTERNET">
Start the server before testing, start the client, and click the button to obtain the server information. This is a very simple example of android socket. You can have a brief understanding of the socket. Please note This note first!