Socket programming on Android

Source: Internet
Author: User

Basic socket programming knowledge:

Mainly divided into server-side programming and client-side programming.

Server programming steps:
1: Create a server socket and bind it to a port (0-1023 is reserved by the system, preferably around 1024)
2: Set the socket listening mode to wait for connection requests
3: communication after accepting the connection request
4: return, waiting to win a connection request

Client programming steps:
1: Create a client socket (specify the Server IP address and port number)
2: Connection (Android will automatically connect when creating a socket)
3: communicate with the server
4: Disable socket

Android Socket Communication Principles:
1: The intermediate Pipeline Connection is implemented through the inputstream/outputstream stream.
2: communication can be performed once the pipeline is established
3: closing the MPs queue also means closing the socket.
4: An exception occurs when a duplicate pipe is created for the same socket.
5: the order in the communication process is very important: the server first obtains the input stream, and then outputs the input stream information to each of its clients.

After the client establishes a connection, it first writes the output stream and then obtains the input stream. Otherwise, an exception with eofexception occurs.


Do not forget to add Internet permissions. Do not forget to add Internet permissions.


ServerCodeWrite:

 

Import Java. io. datainputstream; import Java. io. dataoutputstream; import Java. io. ioexception; import java.net. serversocket; import java.net. socket; import Java. util. arraylist; public class server {static serversocket aserversocket = NULL; // server socet. datainputstream adatainput = NULL; // server input stream that to // receive MSG from client. dataoutputstream adataoutput = NULL; // server output stream That tostatic arraylist list = new arraylist (); public static void main (string [] ARGs) {try {aserversocket = new serversocket (50003); // listen 8888 port. system. out. println ("already listen 50003 port. ");} catch (exception e) {e. printstacktrace ();} int num = 0; while (Num <10) {socket asessionsoket = NULL; try {asessionsoket = aserversocket. accept (); mythread thread = new server (). new mythread (asession Soket); thread. start (); num = List. size ();} catch (ioexception E1) {// todo auto-generated catch blocke1.printstacktrace () ;}} class mythread extends thread {socket asessionsoket = NULL; public mythread (Socket socket) {asessionsoket = socket;} public void run () {try {adatainput = new datainputstream (asessionsoket. getinputstream (); adataoutput = new dataoutputstream (asessionsoket. getoutputstream (); List. Add (adataoutput); While (true) {string MSG = adatainput. readutf (); // read MSG. If (! MSG. equals ("connect... ") {system. out. println ("IP:" + asessionsoket. getinetaddress (); // ip. system. out. println ("receive MSG:" + MSG); For (INT I = 0; I <list. size (); I ++) {dataoutputstream output = (dataoutputstream) list. get (I); output. writeutf (MSG + "----" + list. size ();} If (MSG. equals ("end") break;} adataoutput. writeutf ("") ;}} catch (ioexception e) {// todo auto-generated catch blocke. printstack Trace () ;}finally {try {adatainput. Close (); If (adataoutput! = NULL) adataoutput. Close (); list. Remove (adataoutput); asessionsoket. Close ();} catch (exception E2 ){

Note: To handle multiple clients, multiple threads are used. Each thread maintains a socket connection and communication, and the newly connected socket pipeline is added to the arraylist. The operation on the output stream writes data to all connected clients. Remove the client pipeline with socket disabled from the list.

 


Write client code:

 

Import Java. io. datainputstream; import Java. io. dataoutputstream; import Java. io. ioexception; import java.net. inetsocketaddress; import java.net. socket; import java.net. socketaddress; import java.net. unknownhostexception; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. util. log; import android. view. view; import android. view. view. onclickl Istener; import android. widget. button; import android. widget. edittext; import android. widget. textview; public class socketactivity extends activity {edittext = NULL; button sendbutton = NULL; textview display = NULL; Socket Client = NULL; myhandler; dataoutputstream dout; datainputstream din; public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. clientsocket); edittext = (edittext) findviewbyid (R. id. message); sendbutton = (button) findviewbyid (R. id. send); display = (textview) findviewbyid (R. id. display); sendbutton. setonclicklistener (listener); try {client = new socket ("192.168.0.120", 50003); dout = new dataoutputstream (client. getoutputstream (); din = new datainputstream (client. getinputstream ();} catch (unknownhostexception e) {// Do auto-generated catch blocke. printstacktrace ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();} myhandler = new myhandler (); mythread M = new mythread (); M. start ();} class myhandler extends handler {public myhandler () {}// The subclass must override this method to accept data @ overridepublic void handlemessage (Message MSG) {// todo auto-generated method stublog. D ("myhandler", "handlemessage ...... "); super. ha Ndlemessage (MSG); // you can update uiif (client! = NULL & client. isconnected () {log. I ("handler .. "," * ----- * "); try {dout. writeutf ("connect... "); string message = din. readutf (); If (! Message. equals ("") display. settext (display. gettext (). tostring () + "" + "message sent from the server --:" + message);} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace () ;}}} class mythread extends thread {public void run () {While (true) {try {thread. sleep (1000);} catch (interruptedexception e) {// todo auto-generated catch blocke. printstacktrace ();} message MSG = new message (); socketactivity. this. myhandler. sendmessage (MSG) ;}} onclicklistener listener = new onclicklistener () {@ overridepublic void onclick (view v) {// todo auto-generated method stubstring sendtext = edittext. gettext (). tostring (); try {// din = new datainputstream (client. getinputstream (); dout. writeutf (sendtext);/** display. settext (display. gettext (). tostring () + "" + * "message sent from the server:" + din. readutf (); * // ** display. settext (display. gettext (). tostring () + "" + * "message sent from the server --:" + din. readutf (); */} catch (unknownhostexception e) {// todo auto-generated catch blocke. printstacktrace ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();}}};}

 


 

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.