the step of creating a receiving end udp
* 1. Use DatagramSocket designated port, creating a receiving end
* 2. The preparation containers, packaged in wrap DatagramPacket
* 3, receive packages blocking the receive (DatagramPacket)
*. 4, data analysis
* The released resources
. 1 Package cn.ftf.udp;
2
. 3 Import java.io.IOException;
. 4 Import java.net.DatagramPacket;
. 5 Import java.net.DatagramSocket;
. 6
. 7 / **
. 8 * UDP step of creating a receiving end
9 * 1. Use DatagramSocket designated port, creating a receiver side
10 * 2. preparation container, packaged in wrap DatagramPacket
11 * 3, receive packages blocking the receive (DatagramPacket)
12 is *. 4, data analysis
13 * The release of resources
14 * @author house fly ting
15 * /
16 public class the Receive {
. 17 public static void main (String [] args) throws IOException {
18 is // * 1. Use DatagramSocket designated port, creating a receiver terminal
. 19 DatagramSocket Socket = new new DatagramSocket (6665 );
20 is // * 2. preparation vessel wrapped package into DatagramPacket
21 byte [] = DATAS new new byte [2 * 1024 ];
22 is of DatagramPacket Packet = new new of DatagramPacket (DATAS, 0 , datas.length);
23 is // *. 3, receive packages blocking the receive (of DatagramPacket)
24 Socket.Receive (Packet) ;
25 // * 4, data analysis
26 String msg=new String(datas, 0, packet.getLength());
27 System.out.println(msg);
28 // * 5.释放资源
29 socket.close();
30 }
31 }
* The step of creating the transmit end UDP
* 1. Use DatagramSocket designated port, the transmitting side created
* 2. Preparation data, converted into a byte array
* 3. DatagramPacket encapsulated inclusions, specify the destination
* 4. Send wrapped
* 5. Release resources
1 package cn.ftf.udp;
2
3 import java.io.IOException;
4 import java.net.DatagramPacket;
5 import java.net.DatagramSocket;
6 import java.net.InetAddress;
7
8 /**
9 * udp发送端创建步骤
10 * 1.使用DatagramSocket指定端口,创建发送端
11 * 2.准备数据,转成字节数组
12 * 3.封装成DatagramPacket类包裹,需要指定目的地
13 * 4.发送包裹
14 * 5.释放资源
15 * @author 房廷飞
16 *
17 */
18 public class Send {
19 public static void main(String[] args) throws IOException {
20 // * 1.使用DatagramSocket指定端口,创建发送端
21 DatagramSocket socket=new DatagramSocket(8888);//端口号可以不写,对信息传输没有影响
22 // * 2.准备数据,转成字节数组
23 String datas="hello word!";
24 byte[] by=datas.getBytes();
25 //* 3.封装成DatagramPacket类包裹,需要指定目的地
26 DatagramPacket packet=new DatagramPacket(by, by.length,InetAddress.getByName("localhost"),6665);
27 // * 4.发送包裹
28 socket.send(packet);
29 // * 5.释放资源
30 socket.close();
31 }
32 }
33