Android UDP communication

Source: Internet
Author: User
Tags server port

Android UDP communication is very simple, call the following method can realize the client and server UDP communication,

Just transfer the data to the server into a byte array format and pass it in.

/** client sends UDP data to server * /public static void Sendudpdata (final byte[] bytestosend) {new Thread () {@Override public void run () { try{//IP is the server address inetaddress serveraddress = Inetaddress.getbyname (IP); Port is the server port number int serverport =PORT;                Datagramsocket socket = new Datagramsocket ();                                Socket.setsotimeout (8000); Sendpacket sent packets Datagrampacket Sendpacket = new Datagrampacket (bytestosend,bytestosend.length,serveraddr                Ess,serverport); Receivepacket returned packet datagrampacket receivepacket = new Datagrampacket (New Byte[bytestosend.length],bytest                Osend.length);                int tries = 0;                Boolean receivedresponse = false;                    do{socket.send (Sendpacket);                        try{socket.receive (Receivepacket);                        if (!receivepacket.getaddress () equals (serveraddress)) {throw new IOException ("Packet received from unknown source");                    } Receivedresponse = true;                        }catch (Interruptedioexception e) {tries +=1; LOG.I ("TAG", "Received:" + "time Out, "+ (5-tries));                }}while ((!receivedresponse) && (Tries > 5)); if (receivedresponse) {//here can get the data returned by the server string Receivedata=new string (receivepacket.                    GetData ());                LOG.I ("TAG", "Return Data:" +receivedata);                }else{log.i ("TAG", "NO response--giving up");            } socket.close ();            }catch (Exception e) {e.printstacktrace (); }}}.start ();}

Android UDP communication

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.