1、前面说的SocketChannel、ServerSocketChannel都是针对TCP协议而来的实现,那么今天我们就实战一下UDP协议的NIO非阻塞式网络编程,在NIO中UDP的通道实现类是DatagramChannel。
2、实战案例
1、客户端的实现:
@Test
public void nioNonBlockingClientUDP() throws IOException {
//1、开启一个DatagramChannel 的客户端通道
DatagramChannel datagramChannel = DatagramChannel.open();
//2、配置客户端通道为非阻塞的
datagramChannel.configureBlocking(false);
//3、分配缓冲区,然后存储需要发送到服务端的数据。
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("你好 我是客户端!".getBytes());
buffer.flip();
//4、使用客户端通道发送数据到服务端。
datagramChannel.send(buffer, new InetSocketAddress("127.0.0.1",9898));
buffer.clear();
}
2、服务端的实现:
@Test
public void nioNonBlockingServerUDP() throws IOException {
//1、开启一个UDP的 DatagramChannel 服务端通道
DatagramChannel datagramChannel = DatagramChannel.open();
//2、配置服务端通道为非阻塞的
datagramChannel.configureBlocking(false);
//3、绑定服务端通道 端口为9898
datagramChannel.bind(new InetSocketAddress(9898));
//4、打开一个选择器
Selector selector = Selector.open();
//5、将服务端的 通道 注册到 选择器 上,注册的事件类型是READ类型。
datagramChannel.register(selector, SelectionKey.OP_READ);
//6、轮询选择器的选择数量,只要大于1 就表示有事件需要处理。
while (selector.select() >= 1) {
//7、获取到选择器上所有被选择的 选择键列表,循环处理每一个选择键。
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey selectionKey = iterator.next();
if (selectionKey.isReadable()) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
DatagramChannel currentDatagramChannel = (DatagramChannel) selectionKey.channel();
currentDatagramChannel.receive(buffer);
buffer.flip();
System.out.println(new String(buffer.array(),0, buffer.limit()));
buffer.clear();
}
//8、选择键处理完成后一定要当前循环的选择键。
iterator.remove();
}
}
}
本文地址:https://blog.csdn.net/qq_34978129/article/details/109277829
您可能感兴趣的文章:
- 创建Gradle工程出现Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradleXX'.问题解决
- spring boot 错误:Check your ViewResolver setup
- java实现判断一个整数是几位数,并按照逆序输出
- Please, configure Web Facet first!idea报这错的解决办法!!
- SpringBoot 2.0 报错: Failed to configure a DataSource: 'url' attribute is not specified and no embe
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!
网友评论