Android Getting Started note-network communication-Socket

Source: Internet
Author: User

Learn about sockets in the communication mode of Android today. Last two times we used HttpURLConnection, and httpclient to achieve communication, they are all using the HTTP protocol, sockets are called sockets, the protocol used to have TCP and UDP,TCP and UDP is the difference between TCP is reliable and stable, With the advantages of fault-tolerant processing, so the efficiency is lower. Then UDP is not so stable, when the use of UDP to send data, each send, then the socket just send, will not be sent after the other party received, whether the order is correct, so UDP is called unstable transmission, but its efficiency is very high, because the thing is very simple.

Today we learn socket is using the TCP protocol, the use of sockets in Android is actually using the socket in Java, see the application of packet java.net.*; Will know.


We come to complete a small LAN chat program that contains a server, Android app as a client, a mobile phone to send messages, the server will be forwarded to other phones, very simple. The code is much more, the following is attached, we first see how to use the socket.


Client:

Client socket Use steps:

(1) Socket msocket = new socket (server_ip, server_port); Two parameters for server IP address, and server listener port number, respectively

(2) BufferedReader mbufferreader = new BufferedReader (New InputStreamReader (Msocket.getinputstream ())); The input stream can be obtained through Socket.getinputstream (), and the data sent by the server can be obtained from the socket. In order to be able to read one line, we convert it to bufferreader, we can use Bufferreader.readline () line to fetch the data waiting on the socket.

(3) PrintWriter mprintwriter = new PrintWriter (Msocket.getoutputstream (), true); by Socket.getoutputstream () can get the input stream, you can send data through the socket to the server, where you need to set the PrintWriter standard interface, you can use the Mprintwriter.println ("..." ) to send data directly.

(4) Disconnect the connection after use.

Let's take a look at the example:

Msocket = new Socket (server_ip, server_poart); mbufferreader = new BufferedReader (New InputStreamReader ( Msocket.getinputstream ())); mprintwriter = new PrintWriter (Msocket.getoutputstream (), true);
If you do not report exception that means the linked server has succeeded, you can use Mbufferreader and Mprintwrinter to send and receive data.

Read data:

                while (true) {                     if (null! = (Mstrmsg = Mbufferreader.readline ())) {                         Mstrmsg + = "\ n";                         if (Mstrmsg.trim (). Equals ("Exit")) {                             mhandler.sendmessage (Mhandler.obtainmessage ( 2));                            return;                         }                        mhandler.sendmessage (mhandler.obtainmessage (0));                     }                 }
Send data:

Private View.onclicklistener Sendlistener = new View.onclicklistener () {@Override public void OnClick (View            V) {String str = Metmessage.gettext (). toString (). Trim ();                if (Mprintwriter = = null) {showtoast ("Please connect to server first!");            return;            } mprintwriter.println (str);            Mprintwriter.flush ();        Metmessage.settext (""); }    };
To disconnect the connection:

Showtoast ("Disconnected");    try {mbufferreader.close (); Mprintwriter.close (); Msocket.close (); msocket = Null;if (mgetmessagethread! = null) {    Mgetmessagethread = null;}     }     catch (IOException e) {e.printstacktrace (); }

Service side:

On the server side we need to have a serversocket, which is used to receive the connection request, and when each request is received a socket socket is returned, which can be used to communicate with the client. Note: The server side should be running, and can receive a lot of connected programs, server programs must not be shut down or collapsed, so in the design of the server to consider a lot of things, we just simply processing received a client request connection, and then add it to the list, if you receive a message, Forward the received message to all the other sockets in the list, very simple processing.

Steps to use:

(1) ServerSocket mserversocket = new ServerSocket (serverport); Create a listening connection ServerSocket

(2) Keep listening Mserversocket, using accept () Receive connection, if the connection is detected, start a thread, the return value of the socket incoming, then each thread corresponds to a client, can communicate with the client.

(3) Next, each thread will need to forward the message to all other users in the customer list if it receives the data.

(4) After the client disconnects, clear the customer socket information.

Initiates a listening connection and initiates a thread pool, creates a startup thread when the monitor hears the connection request, and puts it into the thread pool to run:

        try {            mserversocket = New ServerSocket (ServerPort);            mexecutorservice = Executors.newcachedthreadpool ();            system.out.println (" Server Start ... ");            socket client = null;             while (True) {                 client = mserversocket.accept ();                mclientlist.add (client);                 Mexecutorservice.execute (new Threadserver (client));            }         } catch (IOException e) {         &NBSp  e.printstacktrace ();        }
The thread receives the message, and forwards the message:

    Private class Threadserver implements Runnable {        private Socket mclient;        private BufferedReader mbufferedreader;         private printwriter mprintwriter;        private String mstrmsg;         public threadserver (Socket client) throws IOException {            this.mclient = client;             Mbufferedreader = new BufferedReader (new InputStreamReader (            & nbsp;       mclient.getinputstream ());            mstrmsg = "usr:" + this.mClient.getInetAddress () + "Connected"                     + ", total:" + mclientlist.size ();             sendmessage (mstrmsg);        }         private void SendMessage (String msg) throws IOException {             system.out.println (msg);            for (Socket client:mclientlist) {                 Mprintwriter = new PrintWriter (Client.getoutputstream (), true);                mprintwriter.println (msg);            }         }         @Override          public void Run () {            try {                 while (null! = (Mstrmsg = MbufferedreadeR.readline ()) {                    if ( Mstrmsg.trim (). Equals ("Exit")) {                         mstrmsg = "User:" + mclient.getinetaddress () + "exit!"                                  + "total:" + (Mclientlist.size ()-1);                         sendmessage (mstrmsg);                        mprintwriter = New PrintWriter (                                 mclient.getoutputstream (), true);      &nbsP                  mprintwriter.println ("exit");                          Mbufferedreader.close ();                        mprintwriter.close ();                         mclientlist.remove (mclient);                        mclient.close ();                        break;                     } else {    & nbsp;                   mstrMSG = mclient.getinetaddress () + ":" + mstrmsg;               & nbsp;        sendmessage (mstrmsg);                    }                }            } catch (SocketException e) {                 //e.printstacktrace ();             } catch (IOException e) {                e.printstacktrace ();            }         }    }


If there is no network foundation, this understanding is still a little complicated, the following posted the project code, we have to experience it, the use of sockets is actually very simple, mainly logic processing.

Here are a few things to keep in mind:

(1) android2.3 can no longer invoke the network request in the main thread of the UI, will crash directly, so you need to use handler to send message processing

(2) example code placed on your machine may not be able to use, SERVER_IP for the computer in the local area network address, need to modify their own. The Android client needs to be connected to the computer so that the client can find the server.


Code:

http://download.csdn.net/detail/u013647382/8273861


Android Getting Started note-network communication-Socket

Related Article

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.