Sender:
static Integer receiverPort = 18000;
static Integer senderPort = 18001;
static byte[] ipAddress = new byte[] { (byte) 127,(byte) 0, 0, 1 };
public static void main( String[] args )
{
DatagramSocket datagramSocket = null;
DatagramPacket datagramPacket = null;
try {
datagramSocket = new DatagramSocket();
InetAddress address = InetAddress.getByAddress(ipAddress);//.getByName("NCSCND3204VCXD0");
System.out.println("请输入要发送的消息('q'退出):");
Scanner scan = new Scanner(System.in);
while (true) {
if(scan.hasNext()){
String str = scan.next();
if(str.equalsIgnoreCase("q"))
{
System.out.println("退出");
break;
}
byte[] bytes = str.getBytes();
datagramPacket = new DatagramPacket(bytes, bytes.length, address, receiverPort);
datagramSocket.send(datagramPacket);
System.out.println("消息发出...");
ReceiveACK();
}
}
} catch (SocketException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (!datagramSocket.isClosed()) {
datagramSocket.close();
}
}
}
private static void ReceiveACK()
{
DatagramSocket datagramSocket = null;
DatagramPacket datagramPacket = null;
try {
datagramSocket = new DatagramSocket(senderPort);
byte[] bytes = new byte[1024];
datagramPacket = new DatagramPacket(bytes, bytes.length);
datagramSocket.receive(datagramPacket);
byte[] datas = datagramPacket.getData();
String str = new String(datas, 0, datagramPacket.getLength());
System.out.println("服务器回复:"+str);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (!datagramSocket.isClosed()) {
datagramSocket.close();
}
}
}
Receiver:
static Integer receiverPort = 18000;
static Integer senderPort = 18001;
static byte[] ipAddress = new byte[] { (byte) 127,(byte) 0, 0, 1 };
public static void main( String[] args )
{
DatagramSocket datagramSocket = null;
DatagramPacket datagramPacket = null;
try {
while (true) {
datagramSocket = new DatagramSocket(receiverPort);
byte[] bytes = new byte[1024];
datagramPacket = new DatagramPacket(bytes, bytes.length);
datagramSocket.receive(datagramPacket);
byte[] datas = datagramPacket.getData();
String str = new String(datas, 0, datagramPacket.getLength());
System.out.println("接收到:"+str);
datagramSocket.close();
SendACK();
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (!datagramSocket.isClosed()) {
datagramSocket.close();
}
}
}
private static void SendACK()
{
DatagramPacket datagramPacket = null;
DatagramSocket datagramSocket = null;
try {
datagramSocket = new DatagramSocket();
InetAddress address = InetAddress.getByAddress(ipAddress);
byte[] bytes = "我已经收到了!".getBytes();
datagramPacket = new DatagramPacket(bytes, bytes.length, address, senderPort);
datagramSocket.send(datagramPacket);
} catch (SocketException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (!datagramSocket.isClosed()) {
datagramSocket.close();
}
}
}
运行效果:
Sender:
Receiver: