//UDP协议的发送
/*
* 创建发送的Socket对象
* 创建数据并打包:数据,数据长度,ip地址,端口
* 调用方法发送
* 释放资源
*/
public class SendDemo {
public static void main(String[] args) throws IOException {
// 创建发送端的Socket对象
DatagramSocket ds = new DatagramSocket();
// 创建数据并打包
byte[] bys = "hello,heima!".getBytes();
// 创建包对象
DatagramPacket dp = new DatagramPacket(bys, bys.length,
InetAddress.getByName("192.168.0.108"), 10086);
//发送数据
ds.send(dp);
//释放资源
ds.close();
}
}
/*
* 创建接收端Socket对象
* 创建数据包
* 接收数据
* 解析数据,并显示在控制台
* 释放资源
*
*/
public class ReceiveDemo {
public static void main(String[] args) throws IOException {
//创建接收端的Socket对象
DatagramSocket ds = new DatagramSocket(10086);
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);
}
}
| 欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |