Java 中的非阻塞 UDP I/O 与阻塞 UDP I/O [英] Non-blocking UDP I/O vs blocking UDP I/O in Java

查看:26
本文介绍了Java 中的非阻塞 UDP I/O 与阻塞 UDP I/O的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Non-blocking TCP/IP SocketChannels and Selector in NIO help me to handle many TCP/IP connections with small number of threads. But how about UDP DatagramChannels? (I must admit that I'm not very familiar with UDP.)

UDP send operations don't seem to block even if the DatagramChannel is not operating in blocking mode. Is there really a case where DatagramSocket.send(DatagramPacket) blocks due to congestion or something similar? I'm really curious if there's such a case and what the possible cases exist in a production environment.

If DatagramSocket.send(DatagramPacket) doesn't actually block and I am not going to use a connected DatagramSocket and bind to only one port, is there no advantage of using non-blocking mode with DatagramChannel and Selector?

解决方案

It's been a while since I've used Java's DatagramSockets, Channels and the like, but I can still give you some help.

The UDP protocol does not establish a connection like TCP does. Rather, it just sends the data and forgets about it. If it is important to make sure that the data actually gets there, that is the client's responsibility. Thus, even if you are in blocking mode, your send operation will only block for as long as it takes to flush the buffer out. Since UDP does not know anything about the network, it will write it out at the earliest opportunity without checking the network speed or if it actually gets to where it is supposed to be going. Thus, to you, it appears as if the channel is actually immediately ready for more sending.

这篇关于Java 中的非阻塞 UDP I/O 与阻塞 UDP I/O的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆