Java NIO Datagramchannel
Java NIO Datagramchannel is a channel that can send and receive UDP packets. Because UDP is a non-connected network protocol, you cannot read and write to DatagramChannel
other channels by default. instead, it sends and receives packets.
Open Datagramchannel
Open a DatagramChannel代码
:
Datagramchannel channel = datagramchannel.open (); Channel.socket (). Bind (new Inetsocketaddress (9999));
This example opens the DatagramChannel
ability to receive packets on UDP port 9999.
Receive data
You can DatagramChannel
receive data by calling the receive()
method, as follows:
Bytebuffer buf = Bytebuffer.allocate; buf.clear (); channel.receive (BUF) ;
receive()
Method copies the contents of the received packet to the given Buffer中
. If the received packet contains more data than Buffer
can fit, the remaining data is silently discarded.
Send data
You can DatagramChannel
send data by calling the send()
method, as follows:
String newdata ="new string to write to file ..." + system.currenttimemillis (); = Bytebuffer.allocate (buf.clear);buf.put (Newdata.getbytes ()); Buf.flip () ; int bytessent = channel.send (buf,new inetsocketaddress ("at.com", 80));
This example sends a string to the "jenkov.com" Server on UDP port 80. However, nothing is being listened to on the port, so nothing happens. You do not receive a notification that a packet is sent, because UDP has no guarantees for data transfer.
Connect to a specific address
You can connect a DatagramChannel
to a specific address on the network. Because UDP is not connected, the way you connect to an address does not create a true connection like a TCP channel. Instead, it locks you DatagramChannel
, so you can only send and receive packets from a specific address.
For example:
Channel.connect (new inetsocketaddress ("at.com", 80));
When connecting, you can also use read()
and write()
methods, just as you would with traditional channels. You have no warranties regarding the delivery of the data sent. Here are a few examples:
int bytesread = channel.read (buf); int byteswritten = channel.write (BUF);
Java NiO Learning Note eight Datagramchannel