1 package NetWork;
2
3 /*
4 * UDP键盘录入方式发送接数据
5 */
6 import java.io.BufferedReader;
7 import java.io.InputStreamReader;
8 import java.net.DatagramPacket;
9 import java.net.DatagramSocket;
10 import java.net.InetAddress;
11
12 public class Udp_Demo2 {
13 public static void main(String[] args) {
14
15 }
16 }
17
18 /*
19 * 编写一个类,做为UDP的发送端;
20 */
21 class UdpOut2 {
22 public static void main(String[] args) throws Exception {
23 // 1.创建UDPSocket服务,通过DatagrameSocket对象,
24 DatagramSocket ds = new DatagramSocket(2354);
25
26 // 键盘录入
27 BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
28
29 // 定义一个变量,用来接收输入的行数据
30 String line = null;
31 // 循环处理用户输出的数据
32 while ((line = bufr.readLine()) != null) {
33 // 当用户输入的886,就跳出循环,退出键盘录入
34 if ("886".equals(line)) {
35 break;
36 }
37 // 将用户输入的数据转换成字节,封装到byte[]数组中去
38 byte[] buf = line.getBytes();
39
40 // 将接收到的数据封装成数据包,
41 DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress
42 .getByName("192.168.1.101"), 2201);
43
44 // 调用ds的send方法 ,发送数据
45 ds.send(dp);
46 }
47 ds.close();// 关闭资源
48 }
49 }
50
51 /*
52 * 接收端口
53 */
54 class UdpReceive2 {
55 public static void main(String[] args) throws Exception {
56
57 DatagramSocket ds = new DatagramSocket(2201); //建立一个Socket服务,监听发送端口的2201端口
58
59 while(true){
60 byte[] buf = new byte[1024 * 64]; //定义一个数组,用来接收用户发送过来的数据
61 DatagramPacket dp = new DatagramPacket(buf, buf.length); //建立数据包,
62 ds.receive(dp); //调用ds的receive()方法 ,将接收到的数据存储到dp数据包中去
63
64 //下面获取数据
65 String ip = dp.getAddress().getHostAddress();
66 String data = new String(dp.getData(),0,dp.getLength());
67 int prop = dp.getPort();
68 System.out.println("IP地址:"+ip);
69 System.out.println("数据:"+data);
70 System.out.println("端口:"+prop);
71 }
72 }
73 }