服务端
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ProtocolFamily;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.Scanner;
import java.util.Date;
public class Server{
public static void main(String[] args) throws IOException{
DatagramChannel channel = DatagramChannel.open();
channel.bind(new InetSocketAddress(8989));
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
SocketAddress receive = channel.receive(buffer);
buffer.flip();//切换读取数据的模式
String str = new String(buffer.array(), 0, buffer.limit());
System.out.println(new Date());
System.out.println(str);
buffer.clear();//清空缓冲区
buffer.put(("服务器已收到消息("+new Date() +"):" + str).getBytes());
buffer.flip();//切换读取数据的模式