Netty writing a simple chat program (vi)

Source: Internet
Author: User

1. Writing the service side

Server Startup class:"

1  Public classMychatserver {2 3      Public Static voidMain (string[] args)throwsinterruptedexception {4 5 6Eventloopgroup Bossgroup =NewNioeventloopgroup ();7Eventloopgroup Workergroup =NewNioeventloopgroup ();8 9         Try{TenServerbootstrap Serverbootstrap =Newserverbootstrap (); One Serverbootstrap.group (bossgroup,workergroup). AChannel (Nioserversocketchannel.class) -. Childhandler (NewMychatserverinitializer ()); -  theChannelfuture channelfuture = Serverbootstrap.bind (8899). sync (); - Channelfuture.channel (). Closefuture (). sync (); -}finally { - bossgroup.shutdowngracefully (); + workergroup.shutdowngracefully (); -         } +  A  at     } -  -}

Server Initialization class:

1  Public classMychatserverinitializerextendsChannelinitializer<socketchannel> {2 @Override3     protected voidInitchannel (Socketchannel ch)throwsException {4 5Channelpipeline Channelpipeline =ch.pipeline ();6 7Channelpipeline.addlast (NewDelimiterbasedframedecoder (4096, Delimiters.linedelimiter ()));8Channelpipeline.addlast (NewStringdecoder (Charsetutil.utf_8));9Channelpipeline.addlast (NewStringencoder (Charsetutil.utf_8));TenChannelpipeline.addlast (NewMychatserverhandler ()); One  A     } -}

server-side business processing handler: increasing the collection of connection instances Channelgroup

1  Public classMychatserverhandlerextendsSimplechannelinboundhandler<string> {2 3     //Connecting Instance Collections4     Private  StaticChannelgroup Channelgroup =NewDefaultchannelgroup (globaleventexecutor.instance);5 6 7 @Override8     protected voidChannelRead0 (Channelhandlercontext ctx, String msg)throwsException {9 TenChannel Channel =Ctx.channel (); One  AChannelgroup.foreach (CH-A{ -             if(Channel! =ch) { -Ch.writeandflush (channel.remoteaddress () + "send Message" + msg + "\ n"); the}Else{ -Ch.writeandflush ("[Self]" + "\ n"); -             } -         }); +     } -  +  A @Override at      Public voidhandleradded (Channelhandlercontext ctx)throwsException { -  -Channel Channel =Ctx.channel (); -Channelgroup.writeandflush ("[Server]-" + channel.remoteaddress () + "Add \ n"); - Channelgroup.add (channel); -     } in  - @Override to      Public voidHandlerremoved (Channelhandlercontext ctx)throwsException { +  -Channel Channel =Ctx.channel (); theChannelgroup.writeandflush ("[Server-]" + channel.remoteaddress () + "Leave \ n"); *System.out.println ("Channelgroup size" +channelgroup.size ()); $     }Panax Notoginseng  - @Override the      Public voidChannelactive (Channelhandlercontext ctx)throwsException { +Channel Channel =Ctx.channel (); ASystem.out.println (channel.remoteaddress () + "on line \ n"); the     } +  - @Override $      Public voidChannelinactive (Channelhandlercontext ctx)throwsException { $Channel Channel =Ctx.channel (); -System.out.println (channel.remoteaddress () + "downline \ n"); -     } the  - @OverrideWuyi      Public voidExceptioncaught (Channelhandlercontext ctx, throwable cause)throwsException { the cause.printstacktrace (); - ctx.close (); Wu     } -}

2. Writing the Client

Client Startup class:

1  Public classmychatclient {2 3      Public Static voidMain (string[] args)throwsinterruptedexception, IOException {4 5Eventloopgroup Eventloopgroup =NewNioeventloopgroup ();6 7         Try{8Bootstrap Bootstrap =NewBootstrap ();9Bootstrap.group (Eventloopgroup). Channel (Niosocketchannel.class)Ten. Handler (NewMychatclientinitializer ()); One  AChannel channel = Bootstrap.connect ("localhost", 8899). Sync (). Channel (); -  -BufferedReader br =NewBufferedReader (NewInputStreamReader (system.in)); the              for(;;) { -Channel.writeandflush (Br.readline () + "\ r \ n"); -             } -  +}finally { - eventloopgroup.shutdowngracefully (); +         } A  at     } -  -}

Client Initialization class

1  Public classMychatclientinitializerextendsChannelinitializer<socketchannel> {2 @Override3     protected voidInitchannel (Socketchannel ch)throwsException {4 5Channelpipeline Channelpipeline =ch.pipeline ();6 7Channelpipeline.addlast (NewDelimiterbasedframedecoder (4096, Delimiters.linedelimiter ()));8Channelpipeline.addlast (NewStringdecoder (Charsetutil.utf_8));9Channelpipeline.addlast (NewStringencoder (Charsetutil.utf_8));Ten  OneChannelpipeline.addlast (NewMychatclienthandler ());//your own processor. A  -     } -}

Client message receive processing handler:

1  Public class extends Simplechannelinboundhandler<string> {2    @Override     3  protectedvoidthrows  Exception {4        System.out.println ( msg); 5     }6 }

Netty writing a simple chat program (vi)

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.