The introduction of UDP is not explained here.
UDP does not have an actual link between the client and the server, so there is no need to set handler for the connection (Channelpipeline), compared to TCP.
Service side:
1 Public voidRunintPortthrowsexception{2Eventloopgroup Group =NewNioeventloopgroup ();3 Try {4Bootstrap B =NewBootstrap ();5B.group (Group). Channel (Niodatagramchannel.class)6. Option (Channeloption.so_broadcast,true)7. Handler (NewUdpserverhandler ());8 9 B.bind (port). Sync (). Channel (). Closefuture (). await ();Ten } One finally { A group.shutdowngracefully (); - } -}
1 @Override2 Public voidmessagereceived (Channelhandlercontext channelhandlercontext,3Datagrampacket datagrampacket)throwsException {4 //because Netty encapsulates UDP, it receives a Datagrampacket object. 5String req =datagrampacket.content (). toString (charsetutil.utf_8);6 System.out.println (req);7 8 if("Pa PA!!! ". Equals (req)) {9Channelhandlercontext.writeandflush (NewDatagrampacket (Unpooled.copiedbuffer (Ten"Result:", Charsetutil.utf_8), Datagrampacket.sender ()); One } A}
Client:
Public voidRunintPortthrowsexception{Eventloopgroup Group=NewNioeventloopgroup (); Try{Bootstrap b=NewBootstrap (); B.group (Group). Channel (Niodatagramchannel.class). Option (Channeloption.so_broadcast,true). Handler (NewUdpclienthandler ()); Channel CH= B.bind (0). Sync (). Channel (); //broadcast UDP to all machines in the network segment classCh.writeandflush (NewDatagrampacket (Unpooled.copiedbuffer ("Snapped!!!" ", Charsetutil.utf_8),Newinetsocketaddress ("255.255.255.255", Port)). Sync (); if(!ch.closefuture (). Await (15000) {System.out.println ("Query timed out!!! "); } } finally{group.shutdowngracefully (); } }
Public void messagereceived (Channelhandlercontext channelhandlercontext, throws Exception { = datagrampacket.content (). toString (charsetutil.utf_8); if (Response.startswith ("Result:")) { System.out.println (response); Channelhandlercontext.close (); } }
SOURCE download
Source code under SRC/MAIN/JAVA/UNP, divided into the client and the service side, they are basic and netty the Code of the introductory chapters similar, but reduced the use of the relevant decoder.
GitHub Address: Https://github.com/orange1438/Netty_Course
Netty (vi) Use of UDP in Netty