天天看点

NIO边看边记 之 DatagramChannel(十)

DatagramChannel是用于UDP网络的通道。

其打开、绑定、关闭操作跟SocketChannel一样。

由于使用的时UDP因此在读写数据时未必能保证可靠。

1.接收数据

通过receive()方法从DatagramChannel接收数据,如:

ByteBuffer buf = ByteBuffer.allocate();
buf.clear();
channel.receive(buf);
           

从网络上传过来的数据size有可能超过buf的size,超出的部分被抛弃。

2.发送数据

通过send()方法从DatagramChannel发送数据,如:

String newData = "New String to write to file..." + System.currentTimeMillis();
ByteBuffer buf = ByteBuffer.allocate();
buf.clear();
buf.put(newData.getBytes());
buf.flip();
int bytesSent = channel.send(buf, new InetSocketAddress("localhost", ));
           

并不保证一定能发送成功。