Android Network application socket (one)

Source: Internet
Author: User

Socket programming is a basic application of network communication, which requires socket technology to establish network communication both on the mobile side and on the PC side. In this chapter, the small series mainly from the following aspects of the socket to introduce the relevant knowledge:

"What is a socket?", respectively. What are the features of the socket? "," the difference between socket and HTTP and TCP "," Mobile socket demo ". If you write a bad place, please criticize me.

What is a socket? Socket is also called "socket", it is a way of network communication, it is not a protocol, but provides to the programmer to implement TCP/IP encapsulation and data transmission interface. It is used to establish a communication pipeline between the client and the server, so that the application/client can send the request to the servers/another host through this communication pipeline, and the server can make the data transfer and exchange between the two. In Android, we know that every application can operate with multithreading, and multiple threads of an app for network transmissions can have a socket connection, each of which maintains its own socket pipeline for concurrent network traffic. The socket consists of 5 main components: the protocol used by the connection (TCP/UDP), the client IP, the client port number, the server-side IP address, and the server-side port number. In Android, ServerSocket is used on the server side and the socket is used to establish a network connection, and both ends produce a socket object when the connection is successful. Second, the characteristics of the socket and the principle of communication we can see that a socket is established using the protocol can be TCP, or can be UDP. TCP is reliable, and UDP is unreliable, because TCP is established with three handshake, the two sides to establish a communication pipeline can be data transmission, and is bidirectional. UDP in the data transfer is only the application layer sent to the package and the address of the destination, not responsible for the other party to receive. A socket communication establishment can be divided into two parts: client and server.Service Side:1, create a server socket and bind to one of its own port, this port is better than 1024, because the 0~1023 port number is reserved by the system, will be called by some system functions. 2, set up the socket listener, listen to whether there are other client programs to request access to this port ServerSocket. 3, if accepted, then accept the request to establish the connection communication

Client:1. Create a client socket, bind the IP address and port number of the target server to be accessed2, connect the server side (here and the socket connection on the PC is different, do not need to connect (), because the client socket on Android when created, if the creation of the success will automatically call the connection method internally) 3, communication with the service side4. Actively shut down the client socket Understanding the client and the service side of the communication process, we can understand that: the server has been in fact maintained to listen to the status of client requests, the socket connection can only be initiated by the requesting client actively shut down. At both ends of the communication, the data is implemented through InputStream and OutputStream, and first the server receives the input stream and returns the result to the client via the output stream. The client side is to send the output stream first and then receive the input stream. The approximate mode is as follows: Server and Client connection:Server listener-------> client request-------> Establish connectionThird, the difference between the socket and HTTP, TCP first need to know that HTTP is the application layer protocol, the main solution is how to package data. TCP is the Transport layer protocol, the main solution is how to transfer data. Sockets are packages of TCP/IP protocols and are not protocols in themselves. The connection mode of the socket is inconsistent with the HTTP and TCP connection modes. From the previous section has learned that the socket connection is starting from the server listening, and in the TCP aspect, the client and the server connection need to go through three handshake before formally start the transmission of data, and HTTP is based on "request-response" to establish data transmission, what does it mean? Only the first request, the server can send data to the outside, can not actively establish the transmission. In the 0.9, 1.0, and 1.1 eras of HTTP, this connection pattern can be maintained at the time a TCP connection is established, responding to multiple requests. When the socket is a package in the transport layer, the transport layer is primarily TCP and UDP, and when the socket is using the TCP protocol instead of the UDP protocol, a socket connection is actually a TCP connection. Iv. Demo Here we will create a demo to use the socket on Android. Our main function is to write a text in the edit box, and then press the Send button, the last internal implementation through the socket communication mode, feedback to the TextView on the display of the content of the edits. The details inside will be analyzed at the end. The following is an XML layout file:
        Android:id= "@+id/btn_conn"/>    <edittext         android:layout_width= "fill_parent"        android:layout_ height= "Wrap_content"        android:hint= "Please edit the content to be sent here"        android:id= "@+id/et_message"/>        <button         android:layout_width= "fill_parent"        android:layout_height= "wrap_content"        android:text= "send"        Android:id= "@+id/btn_sent"/>        <textview         android:layout_width= "fill_parent"        android:layout_ height= "Wrap_content"        android:id= "@+id/tv"        android:hint= "receive data Sent"/></linearlayout>
The layout effect is as follows:

First of all to describe the functional logic we want to implement: 1, by clicking on the connection to establish the socket communication pipeline 2, in the edit box to enter the content we want to send, press the Send button, the data will be displayed in the text control; 3. Create a thread inside yourself that cannot be updated in the UI thread, causing anr;4, itself as the sender, and as the receiver, the main process is to send the data package, through the OutputStream output transmission, created as the content of the message, and then received by handler, thrown into the message queue, processing time to extract data, UI update. Main functions Handler.sentmessage () and Handler.handmessage (). There is outputstream and InputStream when the data packaging, encoding must be consistent. Chinese 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 EditText 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.containe        R, New Placeholderfragment ()). 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 ();} Toast.maketext (Getapplicationcontext (), "Connect OK", Toast.length_short). Show ();//Bind the socket to its own thread object try {mythread = New MyThread (Clientsocket);} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} Mythread.start ();//start thread//update UI, most of the data work has been given to the Mythread object btnsent.setenabled (tRue); btnconn.setenabled (false); stop = False;}});  Sent Message Btnsent.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) {//TODO Auto-generated method stub//When the button is clicked, it gets the data in the edit box and then submits it to the thread//to package the message first byte[] Msgbuffer = null;try {Msgbuffer = Ed_ Message.gettext (). toString (). GetBytes ("GB2312");} catch (Unsupportedencodingexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} After packaging is complete, add the socket's output stream object try {output = Clientsocket.getoutputstream ();} catch (IOException e) {//TODO auto-generated Catch Blocke.printstacktrace ();} The try {///Output Stream object writes bytes to//either the output stream or the input stream, the operation is byte, and if it becomes a string, you need to build the String Object Output.write (Msgbuffer);} catch (IOException e) {// TODO auto-generated catch Blocke.printstacktrace ();}                Toast.maketext (Getapplicationcontext (), "Send Success", Toast.length_short). Show (); Ed_message.settext ("");}}); After the data is connected and sent, the next step is processing, and the sent data is passed to the message queue by means of Handl, which is then obtained by the Mhandler = new Handler () {public void handlemess Age (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 threading class;    Private class MyThread extends thread{//build your own socket object to use the private socket socket within 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 stubs while (!stop) {buf = new byte[512]; Read the data in InputStream into buf try {this.inputstream.read (BUF);} catch (IOException e) {//TODO auto-generated catch Blocke    . Printstacktrace ();} try {//to parse the stream of characters in the BUF to getThis.str = new String (buf, "GB2312"). Trim ();    catch (Unsupportedencodingexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}    When a thread acquires a inputstream stream from the socket and converts it into a string, the thread acquires the entity content of the message//at which point the thread executes its own mission, which is to create the message and send it out with 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 understanding the logic of the code, I'll take a look at the whole idea:when we click on the connnet, we will create a connection destination IP address and port socket connection, at this time, what data are not, socket OutputStream and InputStream inside are empty. Although our custom threads are started after the connection, and the Run method must be executed, there is no data to receive at this time. when we have edited the writing and clicked on the Sent button, the text in the edit box is wrapped by the string to byte, using the String.getbyte () method, why, because OutputStream and InputStream only accept byte stream data. When the socket's Getoutputstream acquires the OutputStream object, the Write method is executed, and the thread is still executing, and it suddenly discovers that there is data in the connected socket. The InputStream object was obtained by using Getiuptestream, the byte stream was read using the Read method, and finally packaged into a string. after being packaged into a string, the thread performs its own mission, encapsulating it as a message and stuffing it to the main thread's message queue as a message, and the Messenger hanlder of the UI thread completes the SendMessage task. Finally, back to the main thread, the handler object uses the Handlmessage method to display the contents of the message on the TextView.
The above is the whole logic.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Network application socket (one)

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.