Java NIO(十二) DatagramChannel
Java NIO DatagramChannel是可以发送和接收UDP数据包的通道。 由于UDP是无连接的网络协议,所以不能像从其他通道那样默认读取和写入DatagramChannel。 而是发送和接收数据包。 Opening a DatagramChannel 这里是你如何打开一个DatagramChannel: DatagramChannel channel = DatagramChannel.open(); channel.socket().bind(new InetSocketAddress(9999)); 这个例子打开一个DatagramChannel,它可以在UDP端口9999上接收数据包。 Receiving Data 您通过调用其receive()方法接收DatagramChannel的数据,如下所示: ByteBuffer buf = ByteBuffer.allocate(48); buf.clear(); channel.receive(buf); receive()方法会将接收到的数据包的内容复制到给定的Buffer中。 如果收到的数据包中包含的数据多于缓冲区可...