package cn.itcast_04;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class ReceiveDemo {
public static void main(String[] args) throws IOException {
// 创建接收端Socket对象
DatagramSocket ds = new DatagramSocket(12345);
while (true) {
// 创建接收数据包对象
byte[] bys = new byte[1024];
DatagramPacket dp = new DatagramPacket(bys, bys.length);
// 接收数据包
ds.receive(dp);
// 解析数据,并显示在控制台
String ip = dp.getAddress().getHostAddress();
String s = new String(dp.getData(), 0, dp.getLength());
System.out.println("from" + ip + " data is:" + s);
}
// 释放资源
// ds.close();
}
}
package cn.itcast_04;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/*
* 数据来自于键盘录入
* 键盘录入要自已控制录入结束。
*/
public class SedDemo {
public static void main(String[] args) throws IOException {
// 创建发送端Socket对象
DatagramSocket ds = new DatagramSocket();
// 封装键盘录入数据
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while ((line = br.readLine()) != null) {
if ("886".equals(line)) {
break;
}
// 创建数据,并打包
byte[] bys = line.getBytes();
// DatagramPacket dp = new DatagramPacket(bys, bys.length,
// InetAddress.getByName("192.168.31.165"), 12345);
DatagramPacket dp = new DatagramPacket(bys, bys.length,
InetAddress.getByName("192.168.31.255"), 12345);
// 发送数据
ds.send(dp);
}
// 释放资源
ds.close();
}
}