package cn.itcast01;
发送端
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
//udp传输,发送端
public class Demo1 {
public static void main(String[] args) throws IOException {
// 创建socket对象
DatagramSocket ds = new DatagramSocket();
// 打包数据
String s = "你好,网络编程";
DatagramPacket dp = new DatagramPacket(s.getBytes(),
s.getBytes().length, InetAddress.getByName("192.168.1.106"), 10086);
//发送数据
ds.send(dp);
//释放资源
ds.close();
}
}
------------------------------------------------------
package cn.itcast01;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
/*
* 接受数据
*/
public class Demo3 {
public static void main(String[] args) throws IOException {
// 创建端口对象
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();
byte[] bys2 = dp.getData();
String s = new String (bys2,0,dp.getLength());
System.out.println(ip+"----"+s);
ds.close();
}
}
|
|