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", ));
并不保證一定能發送成功。