The simple implementation of the UDP method of Netty frame

Source: Internet
Author: User

Recently in the development of the project to use the local Area Network scan discovery function, and later through the learning through the Netty framework to achieve this function, although very simple but initially did not know how to do, recorded.

Service-Side code:

* * Search implementation, based on Netty UDP/public class Searchserver {public static void Initserver () {//UDP Server, accept the client sent radio T
            ry {Bootstrap b = new Bootstrap ();
            Eventloopgroup Group = new Nioeventloopgroup (); B.group (Group). Channel (niodatagramchannel.class). Option (CHANNELOPTION.SO_BROADCA
            ST, True). Handler (new Udpserverhandler ());
        B.bind (appconstants.search_port). sync (). Channel (). Closefuture (). await ();
        catch (Interruptedexception e) {e.printstacktrace (); }} private static class Udpserverhandler extends Simplechannelinboundhandler<datagrampacket> {@Ov
            Erride protected void messagereceived (Channelhandlercontext ctx, Datagrampacket packet) throws Exception {
            Bytebuf buf = packet.copy (). Content ();
            byte[] req = new byte[buf.readablebytes ()];
            Buf.readbytes (req); String BODY = nEW String (req, "UTF-8");
            LOG.D ("TAG", body);

            System.out.println (body);//print received message//Send messages to client String JSON = "Content sent to client";
            Because the data of the datagram is stored in the form of a character array, the transfer data byte[] bytes = json.getbytes ("UTF-8");
            Datagrampacket data = new Datagrampacket (Unpooled.copiedbuffer (bytes), Packet.sender ()); Ctx.writeandflush (data);//Send Message to client}}

The client code is as follows:

public class Searchclient {public static final int messagereceived = 0x99;

    private int scanport;
    Public searchclient (int scanport) {this.scanport = Scanport;
        private static class ClientHandler extends Simplechannelinboundhandler<datagrampacket> {@Override protected void messagereceived (Channelhandlercontext ctx, Datagrampacket PAC
            KET) throws Exception {String BODY = packet.content (). toString (Charsetutil.utf_8);
            LOG.I ("Search", "body:" + body);
        This receives the contents of the server sent}} public void Sendpackage () {Eventloopgroup group = new Nioeventloopgroup ();
            try {Bootstrap b = new Bootstrap (); B.group (Group). Channel (niodatagramchannel.class). Option (CHANNELOPTION.SO_BROADCA

            ST, True). Handler (new ClientHandler ()); Channel ch = b.bind (0). SynC (). Channel ();
                    Ch.writeandflush (Unpooled.copiedbuffer ("Searh:", Charsetutil.utf_8), new Datagrampacket

            New Inetsocketaddress ("255.255.255.255", Scanport)). sync ();

            LOG.I ("Searh", "Sendpackage ()");  Quoteofthemomentclienthandler'll close the datagramchannel then A//response is received.
            If The channel is not closed within 5 seconds,//print a error message and quit.
            if (!ch.closefuture (). await (5000)) {System.err.println ("Search Request timed out.");
            }}catch (Exception e) {e.printstacktrace ();
        LOG.E ("Search", "an Error occur", e);
        finally {group.shutdowngracefully (); }
    }
}

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.