Java NIO之DatagramChannel

Java NIO中的DatagramChannel是一個能收發UDP包的通道。由於UDP是無鏈接的網絡協議,因此不能像其它通道那樣讀取和寫入。它發送和接收的是數據包。服務器

 

打開 DatagramChannel

下面是 DatagramChannel 的打開方式:網絡

1 DatagramChannel channel = DatagramChannel.open();
2 channel.socket().bind(new InetSocketAddress(9999));

這個例子打開的 DatagramChannel能夠在UDP端口9999上接收數據包。app

接收數據

經過receive()方法從DatagramChannel接收數據,如:socket

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

receive()方法會將接收到的數據包內容複製到指定的Buffer. 若是Buffer容不下收到的數據,多出的數據將被丟棄。spa

發送數據

經過send()方法從DatagramChannel發送數據,如:code

1 String newData = "New String to write to file..." + System.currentTimeMillis();
2  
3 ByteBuffer buf = ByteBuffer.allocate(48);
4 buf.clear();
5 buf.put(newData.getBytes());
6 buf.flip();
7  
8 int bytesSent = channel.send(buf, new InetSocketAddress("jenkov.com"80));

這個例子發送一串字符到」jenkov.com」服務器的UDP端口80。 由於服務端並無監控這個端口,因此什麼也不會發生。也不會通知你發出的數據包是否已收到,由於UDP在數據傳送方面沒有任何保證。ip

鏈接到特定的地址

能夠將DatagramChannel「鏈接」到網絡中的特定地址的。因爲UDP是無鏈接的,鏈接到特定地址並不會像TCP通道那樣建立一個真正的鏈接。而是鎖住DatagramChannel ,讓其只能從特定地址收發數據。get

這裏有個例子:flash

1 channel.connect(new InetSocketAddress("jenkov.com"80));

當鏈接後,也能夠使用read()和write()方法,就像在用傳統的通道同樣。只是在數據傳送方面沒有任何保證。這裏有幾個例子:it

view source

print?

1 int bytesRead = channel.read(buf);
2 int bytesWritten = channel.write(but);
相關文章
相關標籤/搜索