Android Simple Socket Communication Demo

Source: Internet
Author: User

I.INTRODUCTION to Android Socket communication

There are two main ways of communication between Android and Server, one is HTTP communication, the other is socket communication. The biggest difference between the two is that the HTTP connection uses "request-response mode", which is to establish a connection channel on request, and the server can return the data to the client after the client sends a request to the server. And the socket communication is to establish a connection between the two can be directly transmitted data, the connection can realize the active push of information, and do not need each time by the client to send a request to the server. So, what is a socket? Socket, also known as socket, within the program provides a port to communicate with the outside world, that is, port communication. By establishing a socket connection, a channel can be provided for transmitting data from both sides of the communication. The main features of the socket are low data loss rates, simple to use and easy to migrate.

Second, the theoretical things are not much to say, directly let us look at the implementation code!!!! 1

The implementation of the client.

1 //interfaces connected to the server2Runnable Connectthread =NewRunnable () {3         4 @Override5          Public voidrun () {6             //TODO auto-generated Method Stub7             //Initialize Scoket, connect to server8             Try {9Socket =NewSocket (ServerIP, serverport);TenIsconnect =true; One                 //start the Receive thread AIsreceive =true; -Receivethread =Newreceivethread (socket); - Receivethread.start (); theSYSTEM.OUT.PRINTLN ("----Connected success----"); -}Catch(unknownhostexception e) { -                 //TODO auto-generated Catch block - e.printstacktrace (); +}Catch(IOException e) { -                 //TODO auto-generated Catch block + e.printstacktrace (); A             } at              -         } -     }; - //interface for sending messages -Runnable Sendthread =NewRunnable () { -          in @Override -          Public voidrun () { to             //TODO auto-generated Method Stub +             byte[] Sendbuffer =NULL; -             Try { theSendbuffer = Strmessage.getbytes ("UTF-8"); *}Catch(unsupportedencodingexception E1) { $                 //TODO auto-generated Catch blockPanax Notoginseng e1.printstacktrace (); -             } the             Try { +OutStream =Socket.getoutputstream (); A}Catch(IOException e) { the                 //TODO auto-generated Catch block + e.printstacktrace (); -             } $             Try { $ Outstream.write (sendbuffer); -}Catch(IOException e) { -                 //TODO auto-generated Catch block the e.printstacktrace (); -             }Wuyi         } the     }; -  Wu     //Receive Thread -     Private classReceivethreadextendsthread{ About         PrivateInputStream instream =NULL; $          -         Private byte[] buffer; -         PrivateString str =NULL; -          A Receivethread (socket socket) { +             Try { theInstream =Socket.getinputstream (); -}Catch(IOException e) { $                 //TODO auto-generated Catch block the e.printstacktrace (); the             } the         } the @Override -          Public voidrun () { in              while(isreceive) { theBuffer =New byte[512]; the                 Try { About instream.read (buffer); the}Catch(IOException e) { the                     //TODO auto-generated Catch block the e.printstacktrace (); +                 } -                 Try { thestr =NewString (buffer, "UTF-8"). Trim ();Bayi}Catch(unsupportedencodingexception e) { the                     //TODO auto-generated Catch block the e.printstacktrace (); -                 } -Message msg =NewMessage (); theMsg.obj =str; the myhandler.sendmessage (msg); the             } the}
View Code

Service-side implementations.

1     //Send Data Interface2      PublicRunnable runnable=NewRunnable () {3         4 @Override5          Public voidrun () {6             //TODO auto-generated Method Stub7             byte[] by=NULL;8             Try {9                 TenBy=data.getbytes ("GBK"); Oneoustream=Socket.getoutputstream (); A Oustream.write (by); - Oustream.flush (); -}Catch(IOException e) { the                 //TODO auto-generated Catch block - e.printstacktrace (); -             } -         } +     }; -  +     //Receive data thread A      Public classThreaddataextendsThread { at          PublicInputStream InputStream; -          -      - @Override -          Public voidrun () { -             //TODO auto-generated Method Stub in             Super. Run (); -          to                 Try { +ServerSocket ServerSocket =NewServerSocket (4567); -Socket =serversocket.accept (); the                      while(true) { *                         byte[] data =New byte[512]; $InputStream =Socket.getinputstream ();Panax Notoginseng inputstream.read (data); -String strdata =NewString (data, "GBK"). Trim (); the                      +LOG.E ("Connection succeeded", Strdata + ""); AMessage msg =handler.obtainmessage (); themsg.obj=strdata; + handler.sendmessage (msg); -                     } $}Catch(IOException e) { $LOG.E ("Ttttttttttt", E.getmessage ()); - e.printstacktrace (); -                 } the              - Wuyi         } the}
View Code

Android Simple Socket Communication Demo

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.