Java4android Socket Network Communication Foundation

Source: Internet
Author: User

This section mainly introduces socket programming, found that the Java socket programming and C language or some of the different, such as the TCP socket, in Java distinguishes the ServerSocket. But the principle is the same, in the process of processing is very similar, so it is not difficult to understand. We will start from the basics, from how to establish a socket connection, to how to achieve a reasonable design such as in Android, we send a message, and then listen to a reply, how to do not die the UI, this article will be very easy for everyone to present a relatively complete Android Socket programming.

Before entering the socket programming of Java, we cut into the principle and then mention the corresponding code description.

Sockets can be said to be a network-based abstraction, which can be used by the application to read and write data to the network. Just as you can write data to a storage device with a file handler. According to the difference between TCP protocol and UDP protocol, there are different sockets for two protocols in network programming, and one is a message-oriented one for byte stream .


TCP

TCP is mainly a connection-oriented protocol, which contains the functions of establishing and removing connections, guaranteeing the order and correctness of data streams. Each data operation that is intermediate to TCP is equivalent to accessing a data stream. Its most typical feature is the three-time handshake that establishes the connection process. The connection establishment and revocation process for TCP is as follows:


Server SideThe main thing to do on the server side is to establish a communication endpoint, and then wait for the client to send the request. The typical processing steps are as follows:
1. Build a ServerSocket instance that specifies the local port. This socket is used to listen for connection requests on the specified port.
2. Repeat these steps:
A. Call the socket's accept () method to obtain a connection request from the following client. A new connection to the client is established through the socket instance returned by the Accept () method.
B. Using this returned socket instance to get InputStream and outputstream, you can read and write the data separately using these two streams.
C. At the end, call the Close () method of the socket instance to close the socket connection.

Single thread version


The typical sample code for this process is as follows:

1. Constructs a ServerSocket instance, specifying a service port. ServerSocket servsock = new ServerSocket (servport); while (true) {   //2. Call the Accept method to establish a connection to the client           Socket Clntsock = Servsock.accept ();           SocketAddress clientaddress =                    clntsock.getremotesocketaddress ();           SYSTEM.OUT.PRINTLN ("Handling client at" + clientaddress);    3. Gets the inputstream,outputstream of the connection for data read and write            inputstream in = Clntsock.getinputstream ();            OutputStream out = Clntsock.getoutputstream ();            while ((Recvmsgsize = In.read (receivebuf))! =-1)            {                out.write (receivebuf, 0, recvmsgsize);            }       4. End the operation and close the socket.            Clntsock.close ();}  

Multi-threaded versionThe above is a single-threaded version of the server process, but also multi-threaded. The approximate code is as follows:

Try   {file://serversocket server    = new ServerSocket (9998);    int i=1; for    (;;)    {    <span style= "White-space:pre" ></span>socket incoming = Server.accept ();    <span style= "White-space:pre" ></span>new serverthread (Incoming,i). Start ();    Turn on threads to handle client requests <span style= "White-space:pre" ></span>i++;    }    }catch (IOException ex) {ex.printstacktrace ();}   

Client SideThe client request process is a little bit different:
1. Build the socket instance to establish the connection through the specified remote server address and port.
2. Read and write data using the InputStream and OutputStream contained in the socket instance.
3. Call the Close method of the socket instance after the operation is closed.
The sample code is as follows;

1. Establish a socket connection based on the specified server address and port. Socket socket = new Socket (server, servport);//2. InputStream is obtained from the socket instance, and OutputStream is read and written. InputStream in = Socket.getinputstream (); OutputStream out = Socket.getoutputstream (); out.write (data);//3. End of operation, Close Socket.socket.close ();


The above code is a complete client/server structure of the socket communication code.



socket design for non-stuck UIHowever, in the case of socket communication in Android, we can imagine this scenario. I entered a "hello" in the EditText, then I press the Send button, I sent the message to the remote server, and then the server gave me back a "Hello, welcome you!" ”。 What happens when we send out the first message and we block the server waiting there? Is our UI going to get stuck? So, obviously, this kind of design is unreasonable.
Client
Myclientactivity.java file, mainly defines a class that inherits from the thread class to receive data, overwrite the run () method, in the function to receive data, after receiving the data, send a message through handler, receive the message in the UI thread to update the received data. The complete contents are as follows:
Package Com.nan.client;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.os.bundle;import Android.os.handler;import Android.os.Message;import Android.view.view;import Android.widget.button;import Android.widget.edittext;import Android.widget.TextView;    Import Android.widget.toast;public class Myclientactivity extends Activity {private EditText medittext = null;    Private Button Connectbutton = null;    Private Button Sendbutton = null;        Private TextView Mtextview = null;    Private Socket clientsocket = null;        Private OutputStream outstream = null;        Private Handler Mhandler = null;    Private Receivethread mreceivethread = null;        Private Boolean stop = true; /** called when the activity is first created.     */@Override public void OnCreate (Bundle savedinstancestate) {   Super.oncreate (savedinstancestate);                Setcontentview (R.layout.main);        Medittext = (EditText) This.findviewbyid (R.id.edittext);        Mtextview = (TextView) This.findviewbyid (R.id.retextview);        Connectbutton = (Button) This.findviewbyid (R.id.connectbutton);        Sendbutton = (Button) This.findviewbyid (R.id.sendbutton);                      Sendbutton.setenabled (FALSE);            Connection button monitoring Connectbutton.setonclicklistener (new View.onclicklistener () {@Override                 public void OnClick (View v) {//TODO auto-generated Method stub try                {//Instantiate the object and connect to the server Clientsocket = new Socket ("113.114.170.246", 8888); } catch (Unknownhostexception e) {//TODO auto-generated                Catch block E.printstacktrace ();  } catch (IOException e)               {//TODO auto-generated catch block E.printstacktrace (); } displaytoast ("Connection succeeded!                                        ");                Connect button enable connectbutton.setenabled (false);                                Send button Enable sendbutton.setenabled (TRUE);                Mreceivethread = new Receivethread (clientsocket);                stop = false;            Turn on thread Mreceivethread.start ();                }        });            Send Data button listener Sendbutton.setonclicklistener (new View.onclicklistener () {@Override public void OnClick (View v) {//TODO auto-generated method stub byte[] m                Sgbuffer = null;                Gets the contents of the Edittex String text = Medittext.gettext (). toString (); try {//character encoding conversion msgbuffer = Text.getbyteS ("GB2312"); } catch (Unsupportedencodingexception E1) {//TODO auto-generated catch block e1.pr                Intstacktrace (); } try {//Get socket Output stream OU                TStream = Clientsocket.getoutputstream ();                } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();                    } try {                Send data Outstream.write (Msgbuffer);                } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();                }//empty content Medittext.settext (""); Displaytoast ("Sent successfully!            ");                      }        }); Message Processing Mhandler = newHandler () {@Override public void Handlemessage (Message msg) {//Display            Received Content Mtextview.settext ((msg.obj). toString ());            }        }; }//show Toast function private void Displaytoast (String s) {Toast.maketext (this, S, Toast.length_short). Show ()    ;                } private class Receivethread extends Thread {private InputStream instream = null;          Private byte[] BUF;                Private String str = NULL; Receivethread (Socket s) {try {//Get input stream this.instream = S.getinputstream ()            ;            } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();                }} @Override public void Run () {while (!stop) {                                This.buf = new byte[512];               try {     Read input data (blocking) This.inStream.read (THIS.BUF);                } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }//character encoding conversion try {this.str = new String (thi                S.buf, "GB2312"). Trim (); } catch (Unsupportedencodingexception e) {//TODO auto-generated catch block E.prin                Tstacktrace ();                } Message msg = new Message ();                Msg.obj = This.str;                            Send Message Mhandler.sendmessage (msg);                }}} @Override public void OnDestroy () {Super.ondestroy ();            if (mreceivethread! = null) {stop = true;        Mreceivethread.interrupt (); }    }     }

Service SideMyserveractivity.java file, defines two thread subclasses, oneA connection for listening to the client, one for receiving data, other places are similar to Myclientactivity.java. The complete contents are as follows:
Package Com.nan.server;import Java.io.ioexception;import Java.io.inputstream;import java.io.outputstream;import Java.io.unsupportedencodingexception;import Java.net.serversocket;import Java.net.socket;import Android.app.activity;import Android.os.bundle;import Android.os.handler;import Android.os.Message;import Android.view.view;import Android.widget.button;import Android.widget.edittext;import Android.widget.TextView;    Import Android.widget.toast;public class Myserveractivity extends Activity {private TextView iptextview = null;    Private EditText medittext = null;    Private Button Sendbutton = null;        Private TextView Mtextview = null;    Private OutputStream outstream = null;    Private Socket clientsocket = null;        Private ServerSocket mserversocket = null;        Private Handler Mhandler = null;    Private Acceptthread macceptthread = null;    Private Receivethread mreceivethread = null;        Private Boolean stop = true; /** called when the activity is first CREAted.        */@Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                Setcontentview (R.layout.main);        Iptextview = (TextView) This.findviewbyid (R.id.iptextview);        Medittext = (EditText) This.findviewbyid (R.id.sedittext);        Sendbutton = (Button) This.findviewbyid (R.id.sendbutton);        Sendbutton.setenabled (FALSE);                Mtextview = (TextView) This.findviewbyid (R.id.textview);            Send Data button listener Sendbutton.setonclicklistener (new View.onclicklistener () {@Override public void OnClick (View v) {//TODO auto-generated method stub byte[] m                Sgbuffer = null;                Gets the contents of the Edittex String text = Medittext.gettext (). toString ();                try {//character encoding conversion msgbuffer = text.getbytes ("GB2312");        } catch (Unsupportedencodingexception E1) {            TODO auto-generated Catch block E1.printstacktrace (); } try {//Get socket Output stream OU                TStream = Clientsocket.getoutputstream ();                } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();                    } try {                Send data Outstream.write (Msgbuffer);                } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();                }//empty content Medittext.settext (""); Displaytoast ("Sent successfully!                            ");        }        }); Message processing Mhandler = new Handler () {@Override public void handlemessage (Message msg) {switch (msg.what) {case 0: {                        Displays the client IP iptextview.settext ((msg.obj). toString ());                        Enable Send button sendbutton.setenabled (true);                    Break } Case 1: {//Display the received data Mtextview.sette                        XT ((Msg.obj). toString ());                    Break                        }                                 }                                                                       }        };        Macceptthread = new Acceptthread ();                  Turn on the Listener thread Macceptthread.start (); }//show Toast function private void Displaytoast (String s) {Toast.maketext (this, S, Toast.length_short). Show ()    ;      } private class Acceptthread extends Thread {@Override  public void Run () {try {//Instantiate ServerSocket object and set port number to 8888 Mserversocket =            New ServerSocket (8888);            } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }
            while (1)
{
            try {//wait for the client to connect (block) Clientsocket = Mserversocket.accept ();            } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();            } mreceivethread = new Receivethread (clientsocket);            stop = false;                        Turn on the receive thread Mreceivethread.start ();            Message msg = new Message ();            Msg.what = 0;            Get client IP msg.obj = clientsocket.getinetaddress (). gethostaddress ();  Send Message Mhandler.sendmessage (msg);  }}} Private class Receivethread extends Thread {private InputStream Minputstream        = NULL;          Private byte[] BUF;                Private String str = NULL; Receivethread (Socket s) {try {//Get input stream this.minputstream = S.getinputstre            AM ();           } catch (IOException e) {     TODO auto-generated Catch block E.printstacktrace ();                }} @Override public void Run () {while (!stop) {                                This.buf = new byte[512];                Read input data (block Read) try {this.mInputStream.read (BUF);                } catch (IOException E1) {//TODO auto-generated catch block E1.printstacktrace (); }//character encoding conversion try {this.str = new String (thi                S.buf, "GB2312"). Trim (); } catch (Unsupportedencodingexception e) {//TODO auto-generated catch block E.prin                Tstacktrace ();                } Message msg = new Message ();                        Msg.what = 1;                Msg.obj = This.str;  Send Message Mhandler.sendmessage (msg);                          }}} @Override public void OnDestroy () {Super.ondestroy ();            if (mreceivethread! = null) {stop = true;        Mreceivethread.interrupt (); }    }        }
The code above is the realization of the real environment of Android socket communication.
UDP

There are two typical differences between UDP and TCP, one is that it does not need to establish a connection, and that it retains the boundary of the message each time it is sent and received.

Server SideBecause the UDP protocol does not need to establish a connection, its process is as follows:
1. Construct the Datagramsocket instance, specifying the local port.
2. The Receive method of the Datagramsocket instance receives the content of the communication in the middle of the datagrampacket.datagrampacket.
3. Receive and send Datagrampacket through the Datagramsocket send and receive methods.
The typical interaction process code is as follows:
1. Build the Datagramsocket instance, specifying the local port. Datagramsocket socket = new Datagramsocket (servport);//2. Build Datagrampacket messages to be sent and received datagrampacket packet = new Datagrampacket (new Byte[echomax], Echomax); while (true) {//3. Ticker socket.receive (packet); SYSTEM.OUT.PRINTLN ("Handling client at" + packet.getaddress (). Gethostaddress ()    + "on port" + Packet.getport ());//4 . Tweet Socket.send (packet);p acket.setlength (Echomax);}

Client SideThe steps of the UDP client are also relatively simple, including the following 3 steps:
1. Construct the Datagramsocket instance.
2. Send the Datagrampacket message via the Send and receive methods of the Datagramsocket instance.
3. When finished, call the Close method of Datagramsocket to close.
Because unlike TCP, UDP can be sent to different servers at the same local port at the same time, generally do not need to specify the address of the destination server in the Datagramsocket constructor of UDP.
Another important difference for UDP clients is that the TCP client sends an ECHO connection message and then goes into a blocking state when the Read method is called, but UDP does not. Because UDP is allowed to be lost in the middle of the packet. If the message is lost and the process is stuck or suspended, the process will never go down. Therefore, a setsotimeout method is generally set up, specifying how long it will take to abort without receiving the message. You can also read a message by specifying a number, loop through the specified number of times, or discard it if you read it back.

A typical example of a UDP client code is as follows:

1. Constructs a UDP Datagramsocket object datagramsocket socket = new Datagramsocket ();//2. Specify timeout time to prevent entering an infinite wait state socket.setsotimeout (timeout);//3. Construct the message object to send and receive datagrampacket Sendpacket = new Datagrampacket (Bytestosend, Bytestosend.length, ServerAddress, ServPort);D Atagrampacket receivepacket = new Datagrampacket (new Byte[bytestosend.length], bytestosend.length);//4. Specify the number of attempts int tri Es = 0;boolean Receivedresponse = false; Do{socket.send (Sendpacket), try{socket.receive (Receivepacket), if (!receivepacket.getaddress (). Equals ( ServerAddress) {throw new IOException ("Received packet from an unknown source");} Receivedresponse = true;} catch (Interruptedioexception e) {tries + = 1; System.out.println ("Timed Out," + (maxtries-tries) + "");}} while (!receivedresponse && (Tries < maxtries))//Feedback if (receivedresponse) {System.out.println based on receipt of message ("Received:" + New String (Receivepacket.getdata ()));} ELSE{SYSTEM.OUT.PRINTLN ("No response--giving up."); 5. Close Socketsocket.close ();

This time the socket programming said here, inside reference and reference reproduced a lot of other people's things, mark a bit.

Reference:

http://shmilyaw-hotmail-com.iteye.com/blog/1556187

Http://www.cnblogs.com/lknlfy/archive/2012/03/04/2379628.html




Java4android Socket Network Communication Foundation

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.