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 (); }
}
}