Socket for Android network applications (1)

Source: Internet
Author: User

Socket for Android network applications (1)

Socket programming is a basic application of network communication. Both mobile phones and PCs require socket technology to establish network communication. In this chapter, I will introduce the knowledge of socket from the following aspects:

What is socket ?", "What are the characteristics of socket ?", "The difference between socket and Http and TCP" and "Mobile socket Demo ". If the writing is poor, please criticize and correct it.

1. What is socket? Socket is also known as "socket". It is a network communication method. It is not a protocol, but an interface for programmers to implement TCP/IP encapsulation and data transmission. It is used to establish a communication pipeline between the client and the server, so that the application/client can send requests to the server/another host through this communication pipeline. At the same time, the server can also perform corresponding operations, establish data transmission and exchange between the two. In Android, we know that every application can be operated using multiple threads. multiple threads of the app for network transmission can establish a socket connection, each thread maintains its own socket pipeline to implement concurrent network communication. The socket consists of five main components: the protocol used for connection (TCP/UDP), Client IP address, client port number, Server IP address, and server port number. In Android, serverSocket is used on the server and socket is used to establish a network connection. When the connection is successful, both ends will generate a socket object. Ii. socket features and communication principles we can see that the protocol used when a socket is established can be TCP or UDP. TCP is reliable while UDP is unreliable, because three handshakes are required when TCP is established. Both parties establish a communication pipeline to transmit data in two directions. During data transmission, UDP only packs the data sent from the application layer and attaches the destination address. It is not responsible for the recipient's receipt. Communication between a Socket can be divided into two parts: client and server: Server: 1. Create a server socket and bind it to your own port. The port should be greater than 1024, because 0 ~ 1023 the port number is reserved by the system and will be called by some system functions. 2. Establish a socket listener to monitor whether there are other client programs requesting access to the serverSocket on this port. 3. If yes, the request is accepted to establish a connection.

Client: 1. Create a client socket and bind the IP address and port number of the target server to be accessed. 2. connect to the server (which is different from the socket connection on the PC. connect () is not required (), because when the client socket on Android is created, if it is successfully created, the connection method is automatically called internally) 3. Communicate with the server. 4. Take the initiative to close the client socket to understand the communication process between the client and the server. We can all understand that the server actually keeps listening to client requests, the socket connection can only be closed by the client initiating the request. During communication between the two ends, data is implemented through InputStream and OutputStream. First, the server receives the input stream and then returns the result to the client through the output stream. The client sends the output stream before receiving the input stream. The general mode is as follows: connection between the server and the client: server listening -------> client request -------> establish connection 3. The difference between socket and HTTP and TCP requires that HTTP is an application layer protocol, the main solution is how to package data. TCP is the transport layer protocol, which mainly solves the problem of data transmission. Socket is the encapsulation of TCP/IP protocol. It is not a protocol. The socket connection mode is inconsistent with the HTTP and TCP connection modes. From the above section, we have learned that the socket connection starts from server listening. In TCP, the client-server connection must undergo three handshakes before data transmission starts, HTTP enables data transmission based on request-response. What does it mean? The server can send data externally only when a request is sent first. transmission cannot be established actively. In the era when HTTP passes through 0.9, 1.0, and 1.1, this connection mode can be maintained at a TCP connection establishment and respond to multiple requests. When the socket is an encapsulation of the transport layer, the transport layer mainly consists of TCP and UDP protocols. When the socket uses TCP rather than UDP, a socket connection is actually a TCP connection. 4. Demo here we will create a demo and use socket on Android. The main function of our Demo is to write a piece of text in the editing box, then press the send button, and finally implement the communication mode through socket, and feedback to textview to display the edited content. The details will be analyzed at the end. Below is the xml layout file:
Android: id = @ + id/btn_conn/>
 
          
   
 
The layout effect is as follows:

First, describe the functional logic we want to implement: 1. Create a socket communication pipeline by clicking the connection. 2. Enter the content we want to send in the editing box, and press the send button, data is displayed in the text control. 3. You can create a thread internally and cannot update it in the UI thread. This will cause ANR. 4. You are the sender and receiver, the main process is to package and send the data, output and transmit the data through outputstream, and create the content of the message. Then, handler receives the data and throws it into the message queue. during processing, the data is decompressed, ui updates. Handler. sentmessage () and handler. handmessage (). In addition, when outputstream and inputstream are packaged, the encoding must be consistent. You can use GB2312.
The Code is as follows:
Package com. example. mysocketdemo; import java. io. IOException; import java. io. inputStream; import java. io. outputStream; import java. io. unsupportedEncodingException; import java.net. socket; import java.net. unknownHostException; import android. app. activity; import android. app. actionBar; import android. app. fragment; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. text. Editable; import android. view. layoutInflater; import android. view. menu; import android. view. menuItem; import android. view. view; import android. view. viewGroup; import android. widget. button; import android. widget. editText; import android. widget. textView; import android. widget. toast; import android. OS. build; public class MainActivity extends Activity {private TextView TV; private Button btnsent, btnconn; private E DitText ed_message; private OutputStream output; private Socket clientSocket; private Handler mHandler; private MyThread mythread; boolean stop = true; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); if (savedInstanceState = null) {getFragmentManager (). beginTransaction (). add (R. id. container, new PlaceholderFrag Ment ()). commit () ;}init (); // onClickEvent --- connect btnconn. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubtry {clientSocket = new Socket (127.0.0.1, 8888);} catch (UnknownHostException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} Toa St. makeText (getApplicationContext (), connect OK, Toast. LENGTH_SHORT ). show (); // bind the socket to your own thread object try {mythread = new MyThread (clientSocket);} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} mythread. start (); // start thread // update the UI. Most of the data work has been handed over to the mythread object btnsent. setEnabled (true); btnconn. setEnabled (false); stop = false ;}}); // sent Message btnsent. setOnClickListener (new View. onClickLi Stener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stub // when you click the button, the data in the edit box is obtained, then submit it to the thread // package the sent content byte [] msgBuffer = null; try {msgBuffer = ed_message.getText (). toString (). getBytes (GB2312);} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke. printStackTrace ();} // After packaging, add the socket output stream object try {output = clientSocket. getOutputStream ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} try {// The output stream object writes bytes into the // both the output stream and the input stream operate in bytes. If it is converted to a string, you need to build the String object output by yourself. write (msgBuffer);} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} Toast. makeText (getApplicationContext (), sent successfully, Toast. LENGTH_SHORT ). show (); ed_message.setText () ;}}); // after the data is connected and sent, it is processed. The sent data is transmitted to the message Queue through message, then, handl gets mHandler = new Hand. Ler () {public void handleMessage (android. OS. message msg) {TV. setText (msg. obj. toString () ;};};} public void init () {TV = (TextView) findViewById (R. id. TV); btnsent = (Button) findViewById (R. id. btn_sent); ed_message = (EditText) findViewById (R. id. et_message); btnconn = (Button) findViewById (R. id. btn_conn); btnconn. setEnabled (true); btnsent. setEnabled (false);} // custom Thread class; private class MyThread ex Tends Thread {// build your own socket object to use private Socket socket in the Thread; private byte [] buf = null; private InputStream inputstream; String str = null; public MyThread (Socket socket) throws IOException {this. socket = socket; inputstream = this. socket. getInputStream () ;}@ Override public void run () {// TODO Auto-generated method stub while (! Stop) {buf = new byte [512]; // read data in inputstream to buf. try {this. inputstream. read (buf);} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} try {// parse the streams stream in the buf to obtain this. str = new String (buf, GB2312 ). trim ();} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke. printStackTrace ();} // After the Inputstream byte stream from the socket is obtained in the thread and converted to a string, the thread obtains the entity content of the message. // at this time, the thread will execute its own The mission is to create a Message and send the Message msg = new Message (); msg. obj = this. str; mHandler. sendMessage (msg) ;}}@ Override protected void onDestroy () {// TODO Auto-generated method stub if (mythread! = Null) {mythread. interrupt ();} super. onDestroy ();}



After learning about the code logic, let's take a look at the entire idea: After we click connnet, we will create a socket connection to the target IP address and port. At this time, there is no data, both Outputstream and InputStream of socket are empty. Although the custom thread starts after the connection and must execute the run method, there is no data to receive at this time. After we edit the text pen and click the sent button, the text in the edit box will be wrapped in byte by a String. the getbyte () method. Why? Because outputstream and inputstream only accept byte stream data. After the getOutputStream of the socket obtains the outputstream object, it executes the write method to write data, and the thread is still executing. It suddenly finds that there is data in the connected socket, you can use getIupteStream to obtain the inputstream object, read the byte stream using the read method, and finally package it into a string. After being packaged into a string, the thread needs to execute its own mission, that is, to encapsulate it into a message and plug it into the message queue of the main thread in the form of a message, now Hanlder of the UI thread completes the sendmessage task. Finally, return to the main thread. The Handler object displays the message content in textView using the handlmessage method.
The above is the entire logic.

 

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.