The UDP usage of NIO in Java

Source: Internet
Author: User

The Datagramchannel in Java NiO is a channel that can send and receive UDP packets. Because UDP is a non-connected network protocol, it cannot be read and written like other channels. It sends and receives a packet.

Server-side code

Package Com.test.nio;import Java.io.ioexception;import Java.net.inetsocketaddress;import java.nio.ByteBuffer; Import Java.nio.channels.datagramchannel;public class Testudpserver {/** * @param args * @throws Exception  */public s tatic void Main (string[] args) throws Exception {Datagramchannel channel=datagramchannel.open (); Channel.socket (). bind (New Inetsocketaddress (9999)); Bytebuffer buf=bytebuffer.allocate, Buf.clear ();/* Blocking, waiting for data */channel.receive (BUF);/* Set buffer readable */buf.flip ();/* Loop read out all characters */while (buf.hasremaining ()) {System.out.print ((char) buf.get ());}}}
Client code

Package Com.test.nio;import Java.io.ioexception;import Java.net.inetsocketaddress;import java.nio.ByteBuffer; Import Java.nio.channels.datagramchannel;public class Testudpclient {/** * @param args * @throws Exception  */public s tatic void Main (string[] args) throws Exception {Datagramchannel channel=datagramchannel.open (); String newdata= "hello,itbuluoge!" +system.currenttimemillis (); Bytebuffer buf=bytebuffer.allocate (buf.clear); Buf.put (Newdata.getbytes ()); Buf.flip ();/* Send UDP packets */int Bytessent=channel.send (buf, New inetsocketaddress ("127.0.0.1", 9999));}}


Output results


In fact, the above code function is very simple, that is, the server listens, the client sends a UDP packet, if the server is not listening or has been shut down, the client sends will not throw an exception, because UDP is a non-connection-oriented protocol.


The UDP usage of NIO in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.