课后知识点回顾十四 网络编程1

UDP
发送端
System.out.print("发送端:");
try {
Scanner ss = new Scanner(System.in);
String info = ss.next();
DatagramSocket ds = new DatagramSocket();
byte[] b = info.getBytes();
DatagramPacket dp = new DatagramPacket(b, b.length,InetAddress.getByName("172.20.10.13"),1);
ds.send(dp);
ds.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


接收端
System.out.println("接收端:");
try {
DatagramSocket ds = new DatagramSocket(666);
byte[] b = new byte[1024];
DatagramPacket dp = new DatagramPacket(b, b.length);
ds.receive(dp);
byte[] bb = dp.getData();
System.out.println(new String(b,0,b.length));
ds.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

你可能感兴趣的:(课后知识点回顾十四 网络编程1)