2010年9月1日 星期三

Java NIO DatagramChannel

Steps of using DatagramChannel

1.initializing DatagramChannel and bind it to specific port number, and connect it to the destination so that we can perform read and write later through this channel

DatagramChannel channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(9999));
channel.connect(new InetSocketAddress("wallyjue.blogspot", 80));


2. prepare the buffering space for receiving data, note that if the received packet contains more data than the Buffer can contain, the remaining data is discarded silently.
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();

channel.receive(buf);


reference:
1. http://tutorials.jenkov.com/java-nio/index.html
2. http://onjava.com/pub/a/onjava/2002/09/04/nio.html
3. http://openjdk.java.net/projects/nio/javadoc/java/nio/channels/DatagramChannel.html

沒有留言: