receiving end
Address already in use: Cannot bind does not allow port conflicts under the same protocol
1. Create the receiver using the specified port of DatagramSocket
2. Preparing containers to be packaged as Datagram Packets
3. Blocking receive (Datagram Packet p);
4. Analyzing data and restoring byte arrays to corresponding types
getData() returns an array of bytes, getLength() returns the length of the data, and the type is int.
5. Releasing Resources
*/
public class http{ public static void main(String[]args) throws IOException { System.out.println("Receiver promoter..."); //Create interface DatagramSocket server=new DatagramSocket(8888); //Encapsulation package byte[] data=new byte[1024*60]; DatagramPacket packet= new DatagramPacket(data,0,data.length); //Accept parcel server.receive(packet); //Analysis data byte[] datas=packet.getData(); int len=packet.getLength(); ByteArrayInputStream bis=new ByteArrayInputStream(datas); DataInputStream dis=new DataInputStream(new BufferedInputStream(bis)); String s=dis.readUTF(); int age=dis.readInt(); boolean flag=dis.readBoolean(); char ch=dis.readChar(); System.out.println(age+s); //close resource server.close(); }
Basic type: sender
1. Create the sender using the specified port of DatagramSocket
2. Preparing data must be converted into byte arrays and basic types into byte arrays.
3. Preparing containers to be packaged as Datagram Packet packages requires a specified destination (ip address and port)
4. Send a package to send (Datagram Packet p);
5. Releasing Resources
public class client{ public static void main(String[]args) throws IOException { System.out.println("Sender Startup..."); //Create interface DatagramSocket client=new DatagramSocket(9999); //Prepare data and convert it into byte arrays ByteArrayOutputStream baos=new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(baos)); dos.writeUTF("Du Yulong is the most handsome"); dos.writeInt(18); dos.writeBoolean(false); dos.writeChar('q'); dos.flush(); byte[] datas=baos.toByteArray(); //Encapsulation package DatagramPacket packet =new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",8888)); //Send parcel client.send(packet); //Release resources client.close(); } }