Server implementation
Server code:
Importjava.net.*;ImportJava.io.*; Public classudprecv2{/** 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 (); }}Udprecv2.java
Android Client code:
Background:
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;Importjava.net.UnknownHostException;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.EditText;ImportAndroid.widget.TextView; Public classMainactivityextendsActivity {PrivateEditText Medittext =NULL; PrivateTextView Mtextview =NULL; PrivateButton Mbutton =NULL; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Mbutton=(Button) Findviewbyid (R.id.mbutton); Medittext=(EditText) Findviewbyid (R.id.medittext); Mtextview=(TextView) Findviewbyid (R.id.mtextview); Mbutton.setonclicklistener (NewStartsocketlistener ()); } //Start button Monitoring classStartsocketlistenerImplementsonclicklistener{@Override Public voidOnClick (View v) {NewServerthread (). Start (); } } classServerthreadextendsthread{//UDP Protocol@Override Public voidrun () {datagramsocket DS=NULL; 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 8888DS =NewDatagramsocket (8888); //2. Get the text box data and encapsulate the data you want to send into the packet//Send user-entered content to the serverString str=Medittext.gettext (). toString (); byte[] buf =str.getbytes ("GBK"); 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[1024]; Datagrampacket Recvpacket=NewDatagrampacket (Recvbuf, recvbuf.length); Ds.receive (Recvpacket); String Recvstr=NewString (Recvpacket.getdata (), 0, Recvpacket.getlength ()); Mtextview.settext ("Received UDP server: \ t" +recvstr); //4. Close the connection//ds.close (); } Catch(unknownhostexception e) {LOG.E ("UDP errror", "192.168.1.108 is Unkown server!"); } Catch(Exception e) {e.printstacktrace (); } finally { Try{ds.close (); } Catch(Exception e) {e.printstacktrace (); } } } }}Mainactivity.java
Front desk:
<?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" ><!--get input box information and send it out--<EditText Android:id= "@+id/medittext"Android:layout_width= "Fill_parent"Android:layout_height= "40DP"android:cursorvisible= "false"android:editable= "true"Android:ems= "Ten" > </EditText> <TextView Android:id= "@+id/mtextview"Android:layout_width= "Fill_parent"Android:layout_height= "50DP"Android:ems= "Ten" > </TextView> <Button Android:id= "@+id/mbutton"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "UDP Client---send"/></linearlayout>
Activity_main.xml
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>
permission. INTERNET
Similar to the functionality of TCP, it also gets the contents of the text box sent, and echoes back
The difference is that the PC-side display garbled problem is corrected:
The reason: Android side of the default is UDF-8 encoded
PC-side is GBK encoded, so need: To send to the client before the code to UTF8, to the PC-side sent to the code to GBK
Android UDP Communication 2