Android Learning six: Socket usage

Source: Internet
Author: User

The role of 1socket

Getting the server's data over HTTP is not possible in some cases, and all communication with the socket and the server must be mastered.

2. Code

Okay, on the code, there's an explanation in the code, first of all, the simple service-side code.

 PackageOrg.tonny;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public classSockserverImplementsrunnable{Private Static Final intPORT = 55555; @Override Public voidrun () {//for responding to clientsSocket client =NULL; //service-side socketsServerSocket Server =NULL; Try        {            //bind port, ready to accept client connectionsServer =NewServerSocket (PORT);  while(true) {System.out.println ("Wait for connecting ..."); //This operation is blocked and there is a client connection to do the next stepClient =server.accept (); //read data sent by the clientBufferedReader in =NewBufferedReader (NewInputStreamReader (Client.getinputstream ())); String msg=In.readline (); System.out.println ("Client:" +msg); }        }        Catch(Exception e) {System.out.println ("Server Receive:error"); }        finally        {            Try            {                //Close SocketServer.close ();            Client.close (); }            Catch(IOException e) {System.out.println ("Server Receive:error" +e.getmessage ()); }        }    }     Public Static voidMain (string[] args) {thread thread=NewThread (Newsockserver ());    Thread.Start (); }}

followed by the Android client code

 Packageorg.tonny.client;ImportJava.io.BufferedWriter;Importjava.io.IOException;ImportJava.io.OutputStreamWriter;ImportJava.io.PrintWriter;ImportJava.net.Socket;Importjava.net.UnknownHostException;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.widget.EditText; Public classClientactivityextendsactivity{//The information that needs to be sent is written in this control    PrivateEditText Txtinfo =NULL; Private Static Final intPORT = 55555; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (r.layout.activity_client); Txtinfo= (EditText) This. Findviewbyid (R.id.txtinfo); }     Public voidOnbtnsendclick (view view) {String msg=Txtinfo.gettext (). toString (); //not suitable for use on-the-go, direct exception handling, this is because Android 3.0+ above is not recommended to add time-consuming operations in the activity, to interface and data detachment.        More than 4.0 of the communication must be placed in the thread to do it in the UI thread. //workaround, another thread or service handles the socket. Sockclient sock =NewSockclient ("192.168.1.106", PORT, msg);    Sock.start (); }    Private Final classSockclientextendsThread {PrivateString IP; Private intPort; PrivateString msg;  PublicSockclient (String IP,intport, String msg) {             This. IP =IP;  This. Port =Port;  This. msg =msg; } @Override Public voidrun () {Socket client=NULL; Try{LOG.D ("CLIENT", "Connecting ..."); //getting a connection to the serverClient =NewSocket (IP, port); //get the output stream from client sidePrintWriter out =NewPrintWriter (NewBufferedWriter (NewOutputStreamWriter (Client.getoutputstream ())),true);            OUT.PRINTLN (msg); }            Catch(unknownhostexception e) {LOG.E ("CLIENT", "Error", E); }            Catch(IOException e) {LOG.E ("CLIENT", "Error", E); }            Catch(Exception e) {LOG.E ("CLIENT", "Error", E); }            finally            {                Try                {                    if(Client! =NULL&&!client.isclosed ())                    {Client.close (); }                }                Catch(IOException e) {LOG.E ("TCP", "Error", E); }            }        }    }}

It is important to note that the socket operation must be done in a separate thread, otherwise an exception will occur.

3. Summary

Or a little, Android operation socket, should be executed in the thread, otherwise it will be reported abnormal, in order to spend a lot of time debugging, or did not fix, finally asked the degree Niang.

Android Learning six: Socket usage

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.