import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* a端发送“今天星期几”给b端
*/
public class UDPa {
public static void main(String[] args) throws IOException {
//a端绑定9999端口————a端从9999接收消息
DatagramSocket dgSocket = new DatagramSocket(9999);
byte[] bytes = "今天星期几?".getBytes();
// public DatagramPacket(byte buf[], int offset, int length,
// InetAddress address, int port)
DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length,
InetAddress.getLocalHost(), 9998);
dgSocket.send(packet);
byte[] bytes2 = new byte[1024];
//public DatagramPacket(byte buf[], int length)
packet = new DatagramPacket(bytes2,bytes2.length);
dgSocket.receive(packet);
System.out.println("a接收到的信息:"+new String(packet.getData()));
dgSocket.close(); // 记得关闭流!
}
}
import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* b端接收a端发来的消息,并打印
* b再发送给a:“星期一”
*/
public class UDPb {
public static void main(String[] args) throws IOException {
//b端绑定9998端口————b端从9998接收消息
DatagramSocket dgSocket = new DatagramSocket(9998);
byte[] bytes = new byte[1024];
//public DatagramPacket(byte buf[], int length)
DatagramPacket packet = new DatagramPacket(bytes,bytes.length);
dgSocket.receive(packet);
System.out.println("b接收到的信息:"+new String(packet.getData()));
byte[] bytes2 = "今天星期一。".getBytes();
// public DatagramPacket(byte buf[], int offset, int length,
// InetAddress address, int port)
packet = new DatagramPacket(bytes2, 0, bytes2.length,
InetAddress.getLocalHost(), 9999);
dgSocket.send(packet);
dgSocket.close();
}
}