天天看點

Java NIO系列教程(十) Java NIO DatagramChannel

Java NIO中的DatagramChannel是一個能收發UDP包的通道。因為UDP是無連接配接的網絡協定,是以不能像其它通道那樣讀取和寫入。它發送和接收的是資料包。

打開 DatagramChannel

下面是 DatagramChannel 的打開方式:

DatagramChannel channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(80));      

這個例子打開的 DatagramChannel可以在UDP端口80上接收資料包。

接收資料

通過receive()方法從DatagramChannel接收資料,如:

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

receive()方法會将接收到的資料包内容複制到指定的Buffer. 如果Buffer容不下收到的資料,多出的資料将被丢棄。

發送資料

通過send()方法從DatagramChannel發送資料,如:

String newData = "New String to write to file..." + System.currentTimeMillis();

ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip();

int bytesSent = channel.send(buf, new InetSocketAddress("172.0.0.1", 80));      

這個例子發送一串字元到”172.0.0.1”伺服器的UDP端口80。 因為服務端并沒有監控這個端口,是以什麼也不會發生。也不會通知你發出的資料包是否已收到,因為UDP在資料傳送方面沒有任何保證。

連接配接到特定的位址

可以将DatagramChannel“連接配接”到網絡中的特定位址的。由于UDP是無連接配接的,連接配接到特定位址并不會像TCP通道那樣建立一個真正的連接配接。而是鎖住DatagramChannel ,讓其隻能從特定位址收發資料。

channel.connect(new InetSocketAddress("172.0.0.1", 80));      
int bytesRead = channel.read(buf);
int bytesWritten = channel.write(but);