Android's Simple UDP communication

Source: Internet
Author: User

An Android UDP communication programming step

Server side: 1. Create socket

2. Listening port

3. Receiving data

4. Implement data transmission

Client: directly implement data transmission

Two codes to implement a simple Udphelper class

1  PackageCom.br.delphi.centercontrol;2 3 ImportAndroid.os.Handler;4 ImportAndroid.os.Message;5 ImportAndroid.util.Log;6 7 Importjava.io.IOException;8 ImportJava.net.DatagramPacket;9 ImportJava.net.DatagramSocket;Ten Importjava.net.InetAddress; One Importjava.net.SocketException; A Importjava.net.UnknownHostException; -  - /** the * Created by Delphi on 16-6-11. -  */ -  Public classUdphelper { -     PrivateDatagramsocket socket;//declaring a socket +     Privatedatagrampacket Packet; -     PrivateHandler Handler;//Send the information you receive via HANDL to where you need it +  A     PrivateThread Serverthread; at      PublicUdphelper (FinalHandler Handler) -     { -         This. handler=handler; -Serverthread=NewThread (NewRunnable () {//UDP receive Data thread - @Override -             Public voidrun () { in                 while(true) { -                    byte[] Receivebytes =New byte[1024]; toPacket =NewDatagrampacket (receivebytes, receivebytes.length); +                    Try { - socket.receive (packet); theInetAddress client =packet.getaddress (); *String ClientIP = client.gethostaddress ();//get the IP address of the client $                        byte[] Receivedata = Packet.getdata ();//get the data sentPanax NotoginsengString Datastr =NewString (receivedata); -LOG.D ("UDP", ClientIP); theLOG.D ("UDP", datastr); +  AMessage msg =NewMessage ();//send data via message theMsg.what = 0; +Msg.obj =Datastr; - handler.sendmessage (msg); $}Catch(IOException e) { $ e.printstacktrace (); -                    } -                } the  -            }Wuyi        }); the  -     } Wu      Public  voidListen (intPort//initializing the Listening port -     { About         Try { $socket=NewDatagramsocket (port); - Serverthread.start (); -}Catch(SocketException e) { - e.printstacktrace (); A}Catch(IOException e) { + e.printstacktrace (); the         } -     } $  the      Public  voidSendData (byte[] data,string Ip,intPort) {//Send Data the         Try { thepacket=NewDatagrampacket (Data,data.length,inetaddress.getbyname (Ip), port); the             if(socket==NULL) -socket=NewDatagramsocket (); in socket.send (packet); the}Catch(unknownhostexception e) { the e.printstacktrace (); About}Catch(IOException e) { the e.printstacktrace (); the         } the  +     } -  the      Public  voidSendData (String data,string Ip,intPort//Send character data, note the encoding format for sendingBayi     { the         byte[] tmp=data.getbytes (); the SendData (tmp,ip,port); -     } -      Public  voidClose ()//Close Socket the     { the         if(socket!=NULL) the socket.close (); the     } -}


Three simple to use

1  Private  StaticHandler Handler;2     PrivateUdphelper UDP;3 4 @Override5     protected voidonCreate (Bundle savedinstancestate) {6         Super. OnCreate (savedinstancestate);7 Setcontentview (r.layout.activity_main);8 9 Ten  OneButton mode1button=(Button) Findviewbyid (R.id.button); AButton mode2button=(Button) Findviewbyid (r.id.button2); -Button mode3button=(Button) Findviewbyid (r.id.button3); -  the         FinalEditText edittext=(EditText) Findviewbyid (r.id.edittext); -         FinalTextView textview=(TextView) Findviewbyid (R.ID.TEXTVIEW2); -  -Mode1button.setonclicklistener (NewView.onclicklistener () { + @Override -              Public voidOnClick (view view) { +  A             } at         }); -  -Mode2button.setonclicklistener (NewView.onclicklistener () { - @Override -              Public voidOnClick (view view) { -  in  -                //Toast Toast=toast.maketext (This, "Hello",); toTextview.settext ("Hello,world"); +             } -         }); the  *Mode3button.setonclicklistener (NewView.onclicklistener () { $ @OverridePanax Notoginseng              Public voidOnClick (view view) { -                 NewThread (NewRunnable () { the @Override +                      Public voidrun () { AString str= "Hello"; the                         byte[] Data=str.getbytes (); +Udp.senddata (data, "192.168.0.107", 9000); -                     } $ }). Start (); $  -             } -         }); the  -Handler=NewHandler () {Wuyi @Override the              Public voidhandlemessage (Message msg) -             { Wu                 if(msg.what==0) -                 { About Textview.settext ((String) msg.obj); $                 } -             } -  -         }; Audp=NewUdphelper (handler); +Udp.listen (8000); the  -}




Android's Simple UDP communication

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.