UDP接收数据实例
欢迎使用Markdown编辑器写博客
public void receiveNio() throws SocketException {
Selector selector = null;//Selector(选择器)是Java NIO中能够检测一到多个NIO通道,并能够知晓通道是否为诸如读写事件做好准备的组件。这样,一个单独的线程可以管理多个channel,从而管理多个网络连接。
try {
DatagramChannel channel = DatagramChannel.open();//DatagramChannel是一个能收发UDP包的通道。
DatagramSocket socket = channel.socket();//Java使用DatagramSocket代表UDP协议的Socket,DatagramSocket本身只是码头,不维护状态,不能产生IO流,它的唯一作用就是接收和发送数据报,Java使用DatagramPacket来代表数据报,DatagramSocket接收和发送的数据都是通过DatagramPacket对象完成的。
channel.configureBlocking(false);//在该socket上的读写都不阻塞,也就是读写操作立即返回,无论有没有数据。
socket.bind(new InetSocketAddress(udpPort));//DatagramSocket绑定端口
socket.setReceiveBufferSize(udpBufferSize);//udp,如果包大小超过了缓冲区大小会被丢弃也就是超过512M的包会被丢弃
selector = Selector.open();
channel.register(selector, SelectionKey.OP_READ); //设置成读取操作 ,为了将Channel和Selector配合使用,必须将channel注册到selector上
ByteBuffer byteBuffer = ByteBuffer.allocate(10240);
Set selectedKeys = null;
udpLastTime=System.currentTimeMillis();
while (true) {
try {
int eventsCount = selector.select();
if (eventsCount > 0) {
selectedKeys = selector.selectedKeys(); //一旦调用了select()方法,并且返回值表明有一个或更多个通道就绪了,然后可以通过调用selector的selectedKeys()方法,访问“已选择键集(selected key set)”中的就绪通道。如下所示:
Iterator iterator = selectedKeys.iterator();
while (iterator.hasNext()) {
SelectionKey sk = (SelectionKey) iterator.next();
iterator.remove();
byteBufferReceive(sk, byteBuffer);
}
}
} catch (Exception e) {
logger.error("BUG...BUG...BUG... NioReceiveEventThread#receiver() " + e.getMessage());
} finally {
if (selectedKeys != null) {
selectedKeys.clear();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}