1 package WebProgramingDemo;
2
3 import java.io.IOException;
4 import java.net.DatagramPacket;
5 import java.net.DatagramSocket;
6 import java.net.InetAddress;
7
8 public class UDPSendDemo {
9
10 /**
11 * @param args
12 * @throws IOException
13 */
14 /*
15 * 创建UDP传输的发送端的步骤;
16 * 1.建立UDP的socket服务
17 * 2.明确要发送的数据
18 * 3.将数据封装成数据包
19 * 4.用socket服务的send方法将数据包发送出去
20 * 5.关闭资源
21 */
22 public static void main(String[] args) throws IOException {
23
24 System.out.println("发送端启动。。。");
25 /*
26 * 创建UDP传输的发送端的步骤:
27 */
28 //1.建立UDP的socket服务
29 DatagramSocket ds = new DatagramSocket(8888);
30
31 // 2.明确要发送的数据
32 String s1 = "UDP 传输显示!";
33 // 3.将数据封装成数据包
34 byte buf[] = s1.getBytes();
35 DatagramPacket dp = new DatagramPacket(buf, buf.length,
36 InetAddress.getByName("192.168.2.103"), 10000);
37 // 4.用socket服务的send方法将数据包发送出去
38 ds.send(dp);
39 // 5.关闭资源
40 ds.close();
41
42 }
43
44 }