A Java NIO Datagramchannel is a channel that can send and receive UDP packets. Since UDP is a connection-less network protocol, you cannot just by default read and write to a datagramchannel like you D O from the other channels. Instead you send and receive packets of data.
Opening a Datagramchannel
Here's how you open a Datagramchannel:
Datagramchannel channel = datagramchannel.open (); Channel.socket (). Bind (new inetsocketaddress ( 9999));
This example opens a Datagramchannel which can receive packets on UDP port 9999.
Receiving Data
You receive the data from a datagramchannel by calling it receive () method, like this:
Bytebuffer buf = Bytebuffer.allocate; buf.clear (); channel.receive (BUF) ;
The receive () method would copy the content of a received packet of data into the given Buffer. If the received packet contains more data than the Buffer can contain, the remaining data is discarded silently.
Sending Data
You can send the data via a datagramchannel by calling it Send () method, like this:
String NewData = "New String to write to file ..." + System.currenttimemillis (); = Bytebuffer.allocate (buf.clear);buf.put (Newdata.getbytes ()); Buf.flip () ; int New Inetsocketaddress ("jenkov.com", 80));
This example sends the string to the ' jenkov.com ' server on UDP Port 80. Nothing was listening on this port though, so nothing would happen. You won't be notified of whether the send packet is received or not, since UDP does isn't make no guarantees about deli Very of data.
Connecting to a specific Address
It is possible to "connect" a datagramchannel to a specific address on the network. Since UDP is connection-less, this from connecting to an address does not create a real connection, like with a TCP Chan Nel. Rather, it locks your datagramchannel so can only send and receive data packets from one specific address.
Here are an example:
Channel.connect (new inetsocketaddress ("jenkov.com", 80));
When connected can also use the read () and write () method, as if you were using a traditional channel. You just don ' t has any guarantees about delivery of the sent data. Here is a few examples:
int bytesread = Channel.read (BUF);
int byteswritten = channel.write (BUF);
Java NIO Datagramchannel