Code all from: http://825635381.iteye.com/blog/2046882, here thank you very much, I ran the test under, very correct, thank you AH
Service-Side program:
PackageUdpserver;ImportJava.io.*;Importjava.net.*;/*** Service side * 1, create service + port * 2, prepare to accept container byte array * 3, package the receiving container into package Datagrampacket * 4, accept data * 5, parse data convert byte array to--------"Various types of data * 6. Releasing Resources*/ Public classserver { Public Static voidMain (string[] args)throwsIOException {//1. Create a service + portDatagramsocket Server =NewDatagramsocket (9999); //2. Prepare to accept containers byte[] container =New byte[1024]; //3. Package Datagrampacket (byte buf[], int length)Datagrampacket packet =NewDatagrampacket (container, container.length); //4. Acceptance of data (blocked acceptance)server.receive (packet); //5. Analyze Data Doubledata =convert (Packet.getdata ()); SYSTEM.OUT.PRINTLN (data); //6. Releasing ResourcesServer.close (); } Public Static DoubleConvertbyte[] data)throwsioexception {datainputstream dis=NewDataInputStream (Newbytearrayinputstream (data)); Doublenum =dis.readdouble (); Dis.close (); returnnum; } }
Client program:
PackageUdpClient;ImportJava.io.*;Importjava.net.*;/*** String data type of communication * 1, create client + port * 2, prepare data byte array * 3, package data and specify destination and port to send * 4, send * 5, Release * * Think: Send type of data how to deal with object numbers Wait * 1, create client + port * 2, prepare data to convert various types of data into--------byte array *************************************** * 3, package data and specify the destination and port to send * 4, Send * 5, Release*/ Public classClient { Public Static voidMain (string[] args)throwsIOException {//1. Create a client + portDatagramsocket client =NewDatagramsocket (8888); //2. Prepare the data byte array to be sent DoubleD = 123.2345; byte[] data =convert (d); //3. Package The data and specify the destination and port to send Datagrampacket (byte buf[], int length, inetaddress address, int port)InetAddress address = Inetaddress.getbyname ("127.0.0.1"); Datagrampacket Packet=NewDatagrampacket (data, data.length, address, 9999); //4. Sendclient.send (packet); //5. ReleaseClient.close (); } /*** Byte array datasource + data output stream *@paramd *@return * @throwsIOException*/ Public Static byte[] CONVERT (DoubleDthrowsIOException {byte[] data =NULL; //Write DataBytearrayoutputstream BOS =NewBytearrayoutputstream (); DataOutputStream dos=NewDataOutputStream (BOS); Dos.writedouble (d); Dos.flush (); //Get Datadata =Bos.tobytearray (); Dos.close (); returndata; } }
The server-side console displays the number that the client issued:
123.2345
Java UDP sends fractional numbers (harder)