前言
UDP,不定向传输,其实也差不多,就是可能会丢包,适用用对丢包要求不是太高的场景,例如视频会议啊什么的,掉个一两帧你也看不出来。
闲话少说,还是上代码吧
服务端
package com.lyrics;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Server {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket(2345); // 监听指定端口
System.out.println("server is running...");
for (;;) {
// 接收:
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
ds.receive(packet);
String cmd = new String(packet.getData(), packet.getOffset(), packet.getLength(), StandardCharsets.UTF_8);
// 发送:
String resp = "bad command";
switch (cmd) {
case "date":
resp = LocalDate.now().toString();
break;
case "time":
resp = LocalTime.now().withNano(0).toString();
break;
case "datetime":
resp = LocalDateTime.now().withNano(0).toString();
break;
case "weather":
resp = "rain, 20C.";
break;
}
System.out.println(cmd + " >>> " + resp);
packet.setData(resp.getBytes(StandardCharsets.UTF_8));
ds.send(packet);
}
}
}
客户端
package com.lyrics;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Client {
public static void main(String[] args) throws IOException, InterruptedException {
DatagramSocket ds = new DatagramSocket();
ds.setSoTimeout(1000);
ds.connect(InetAddress.getByName("localhost"), 2435); // 连接指定服务器和端口
DatagramPacket packet = null;
for (int i = 0; i < 5; i++) {
// 发送:
String cmd = new String[] { "date", "time", "datetime", "weather", "hello" }[i];
byte[] data = cmd.getBytes();
packet = new DatagramPacket(data, data.length);
ds.send(packet);
// 接收:
byte[] buffer = new byte[1024];
packet = new DatagramPacket(buffer, buffer.length);
ds.receive(packet);
String resp = new String(packet.getData(), packet.getOffset(), packet.getLength());
System.out.println(cmd + " >>> " + resp);
Thread.sleep(1500);
}
ds.disconnect();
System.out.println("disconnected.");
}
}