Netty to address channel management, broadcast messages

Source: Internet
Author: User

The Channelgroup interface is provided in Netty, which inherits the set interface, so you can manage all the connected channel on the server side by Channelgroup and then broadcast the message to all connected channel.

Server side:

public class Broadcastserver {public static void run (int port) {Eventloopgroup boss = new Nioeventloopgroup ();        Eventloopgroup worker = new Nioeventloopgroup ();            try {serverbootstrap bootstrap = new Serverbootstrap ();                     Bootstrap.group (boss, worker). Channel (Nioserversocketchannel.class)//Set channel Type . option (Channeloption.so_backlog, 1024)//Set channel property. Childhandler (NE W channelinitializer<socketchannel> () {@Override protected void INITC                            Hannel (Socketchannel ch) throws Exception {Channelpipeline pipeline = Ch.pipeline ();                            Pipeline.addlast ("Framedecoder", New Lengthfieldbasedframedecoder (Integer.max_value, 0, 4, 0, 4));                            Pipeline.addlast ("Frameencoder", New Lengthfieldprepender (4)); Pipeline.addlAST ("Decoder", New Stringdecoder (Charsetutil.utf_8));                            Pipeline.addlast ("encoder", New Stringencoder (Charsetutil.utf_8));                        Pipeline.addlast (New Broadcastchannelhandler ());            }                    });            Channelfuture channelfuture = Bootstrap.bind (port). sync ();            if (Channelfuture.isdone ()) {System.out.println (String.Format ("Server bind port%s sucess", port));            } Channel Channel = Channelfuture.channel ();        /**closefuture asynchronously closes/channel.closefuture (). sync ();        } catch (Interruptedexception e) {e.printstacktrace ();            } finally {boss.shutdowngracefully ();        Worker.shutdowngracefully ();    }} public static void Main (String []args) {broadcastserver.run (8080); }}public class Broadcastchannelhandler extends Channelinboundhandleradapter {private static final Gson Gson = NEW Gsonbuilder (). Create ();        private static final SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");        Private static final Atomicinteger response = new Atomicinteger ();        @Override public void channelactive (Channelhandlercontext ctx) throws Exception {Channel ch = ctx.channel (); if (channelgroups.size () > 0) {Message msg = new Message (ch.remoteaddress (). toString (). substring (1),            Sdf.format (New Date ()));        Channelgroups.broadcast (Gson.tojson (msg), New Channelmatchers ());    } channelgroups.add (CH); } @Override public void Channelread (Channelhandlercontext ctx, Object msg) throws Exception {Channel ch = ct        X.channel (); if (Channelgroups.contains (CH) && string.valueof (msg). Equals ("Welcome")) {System.out.println (string.fo Rmat ("Receive [%s] from [%s] at [%s]", String.valueof (msg), Ch.remoteaddress (). Tostrin g (). substring (1), SDF.FOrmat (New Date ())));        Response.incrementandget ();            } synchronized (response) {System.out.println (Response.get () + "\ T" + channelgroups.size ()); if (response.get () = = Channelgroups.size ()-1) {System.out.println ("server close all connected channel"                );                Channelgroups.disconnect ();            Response.set (0); }}} @Override public void Channelreadcomplete (Channelhandlercontext ctx) throws Exception {C    Tx.flush ();    } @Override public void handlerremoved (Channelhandlercontext ctx) throws Exception {ctx.close (); } @Override public void Exceptioncaught (Channelhandlercontext ctx, Throwable cause) throws Exception {CA        Use.printstacktrace ();        Channelgroups.discard (Ctx.channel ());    Response.decrementandget (); } public static class Channelmatchers implements Channelmatcher {@Override public boolean matches (ChAnnel Channel) {return true; }            }    }

The server side actively shuts down the connected channel after the server receives the response from all connected clients to the broadcast message

Client:

public class Client{private static final String host = "127.0.0.1";p rivate static final int port = 8080;private static fin Al Executorservice es = executors.newfixedthreadpool (5);p ublic static void Start () {for (int i = 0; i < 5; i++) {Es.exe Cute (new Task ());} Es.shutdown ();} public static class Task implements Runnable {@Overridepublic void run () {Eventloopgroup group = new Nioeventloopgroup (); t ry {Bootstrap Bootstrap = new Bootstrap (); Bootstrap.group (group). Channel (niosocketchannel.class). Option ( Channeloption.tcp_nodelay, True). Handler (new channelinitializer<socketchannel> () {@Overrideprotected void Initchannel (Socketchannel ch) throws Exception {Channelpipeline pipeline = Ch.pipeline ();p ipeline.addlast (" Framedecoder ", New Lengthfieldbasedframedecoder (Integer.max_value, 0, 4, 0, 4));p ipeline.addlast (" Frameencoder ", new Lengthfieldprepender (4));p Ipeline.addlast ("Decoder", New Stringdecoder (charsetutil.utf_8));p ipeline.addlast (" Encoder ", New Stringencoder (charsetutil.utf_8));pIpeline.addlast (New Simpleclientchannelhandler ());}); Channelfuture channelfuture = Bootstrap.connect (host, port). sync (); if (Channelfuture.issuccess ()) { System.out.println (String.Format ("Connect server (%s:%s) sucess", host, Port));} Channelfuture.channel (). Closefuture (). sync (); catch (Interruptedexception e) {e.printstacktrace ();} finally {group.shutdowngracefully ();}}} public static void Main (String []args) {Client.start ();}} public class Simpleclientchannelhandler extends Channelinboundhandleradapter {@Overridepublic void Channelread ( Channelhandlercontext ctx, Object msg) throws Exception {Channel channel = Ctx.channel (); System.out.println (String.Format ("Client (%s) receive message [%s]", Channel.localaddress (). toString (). SUBSTRING (1) , String.valueof (msg))); System.out.println (); Ctx.writeandflush (string.valueof ("Welcome")); @Overridepublic void handlerremoved (Channelhandlercontext ctx) throws Exception {Ctx.disconnect (ctx.newpromise ()); Ctx.close (); System.out.println (String.Format ("Client(%s) Close sucess ", Ctx.channel (). LocalAddress (). toString (). substring (1)));}} 

This article uses the Channelgroups helper class to manage the server-side channel that is connected, and the code is implemented as follows:

public class Channelgroups {private static final channelgroup Channel_group = new Defaultchannelgroup ("Channelgroups",        Globaleventexecutor.instance);    public static void Add (Channel channel) {Channel_group.add (channel);    } public static Channelgroupfuture broadcast (Object msg) {return Channel_group.writeandflush (msg); } public static Channelgroupfuture broadcast (Object msg, channelmatcher matcher) {return Channel_group.writ    Eandflush (msg, matcher);    } public static Channelgroup flush () {return Channel_group.flush ();    public static Boolean discard (channel Channel) {return channel_group.remove (channel);    } public static Channelgroupfuture disconnect () {return channel_group.disconnect (); } public static Channelgroupfuture disconnect (Channelmatcher matcher) {return Channel_group.disconnect (MATC    Her); } public static Boolean contains (Channel channel) {REturn Channel_group.contains (CHANNEL);    } public static int size () {return channel_group.size (); }}

Netty to resolve channel management, broadcast messages

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.