Android UDP communication

Source: Internet
Author: User

Function:

Achieve a single pitch:

Importjava.net.*;ImportJava.io.*; Public classudprecv{/** Create the receive side of the UDP transmission * 1. To establish a UDP socket service because it is to receive data, you must specify the port number * 2, create a packet, to store the received data. Easily process data with packet objects * 3, use the Receive method of the socket service to store the received data in a packet * 4, resolve data in a packet by means of a packet * 5, close the resource * throw a big exception: IOException 
    */     Public Static voidMain (string[] args)throwsioexception{//1, create the UDP socket serviceDatagramsocket ds =NewDatagramsocket (10000); //2. Create a packet        byte[] buf =New byte[1024]; Datagrampacket DP=NewDatagrampacket (buf,buf.length); //3, use the Received method to store the packet in a packetDs.receive (DP);//Block Type//4. Parse the data in the packet object by means of the methodString IP =dp.getaddress (). gethostaddress (); intPort =Dp.getport (); String content=NewString (Dp.getdata (), 0, Dp.getlength ()); SYSTEM.OUT.PRINTLN (IP+ "::" +port+ ":" +content); /*send back phone data*/        //first get the port and addressInetAddress addr =dp.getaddress (); String Sendstr= "Hello!" I am the server "; byte[] sendbuf; SendBuf= Sendstr.getbytes ("Utf-8");//must convert UTF8, otherwise android display garbledDatagrampacket Sendpacket=NewDatagrampacket (SendBuf, sendbuf.length, addr, port);        Ds.send (Sendpacket); //5 Closing ResourcesDs.close (); }}
Udprecv.java

Android Client Backend code:

 Packagecom.simpleclientudp;ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.OutputStreamWriter;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress;ImportJava.net.Socket;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.widget.EditText; Public classMainactivityextendsActivity {EditText show; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Show=(EditText) Findviewbyid (r.id.show); NewThread () {@Override Public voidrun () {Try            {                //1.udpsocket service object, created using Datagramsocket, can indicate local IP and port//of course it can be done without specifying that it has been tested successfully//now just indicate that the phone port is 8888Datagramsocket ds =NewDatagramsocket (8888); //2. Encapsulate the data you want to send into a packetString str = "UDP tranmsimit,i am Mobilephone"; byte[] buf =str.getbytes ("Utf-8"); Datagrampacket DP=NewDatagrampacket (Buf,buf.length,inetaddress.getbyname ("192.168.1.108"), 10000); //3.udp Send, use socket service to send data packetsDs.send (DP); /*Receive Data*/                byte[] Recvbuf =New byte[100]; Datagrampacket Recvpacket=NewDatagrampacket (Recvbuf, recvbuf.length);                Ds.receive (Recvpacket); String Recvstr=NewString (Recvpacket.getdata (), 0, Recvpacket.getlength ()); Show.settext ("Received: \ T" +recvstr); //4. Close the connectionDs.close (); }            Catch(IOException e) {e.printstacktrace ();    }}}.start (); }}

Front Code:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"android:orientation= "Vertical"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent" > <EditText Android:id= "@+id/show"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"android:cursorvisible= "false"android:editable= "false"Android:ems= "Ten" > <requestfocus/> </EditText> <Button Android:id= "@+id/button1"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "UDP Client"/></linearlayout>
View Code

Permission code:

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "Http://schemas.android.com/apk/res/android" Package= "COM.SIMPLECLIENTUDP"Android:versioncode= "1"Android:versionname= "1.0" > <uses-SDK Android:minsdkversion= "14"android:targetsdkversion= "/>" <uses-permission android:name= "Android.permission.INTERNET"/> <Application Android:allowbackup= "true"Android:icon= "@drawable/ic_launcher"Android:label= "@string/app_name"Android:theme= "@style/apptheme" > <Activity Android:name=". Mainactivity "Android:label= "@string/app_name" > <intent-filter> <action android:name= "Android.intent.action.MA In "/> <category android:name=" Android.intent.category.LAUNCHER "/> </intent-filter&        Gt </activity> </application></manifest>
View Code

Effect:

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.