Netty Realization Chat function

Source: Internet
Author: User

Netty is a Java NIO Client server framework that allows you to quickly and easily develop network applications such as server and client protocols. Netty greatly simplifies the development of network programs such as the development of TCP and UDP socket services. For more information on Netty, refer to the Netty 4.x User Guide (https://github.com/waylau/netty-4-user-guide)

Below, fast implementation of a chat applet based on Netty.

Get ready
    • JDK 7+
    • Maven 3.2.x
    • Netty 4.x
    • Eclipse 4.x
Service side

Let's start with the implementation of the handler (processor), handler is generated by Netty to handle I/O events.

Simplechatserverhandler.java
PublicClassSimplechatserverhandlerExtendssimplechannelinboundhandler<string> {(1)Publicstatic Channelgroup channels =New Defaultchannelgroup (globaleventexecutor.instance);@OverridePublicvoidhandleradded(Channelhandlercontext CTX)Throws Exception {(2) Channel incoming = Ctx.channel ();Broadcast a message to multiple Channelschannels.writeandflush ("[SERVER]-" + incoming.remoteaddress () +"Add \ n"); Channels.add (Ctx.channel ()); }@OverridePublicvoidHandlerremoved(Channelhandlercontext CTX)Throws Exception {(3) Channel incoming = Ctx.channel ();Broadcast a message to multiple Channelschannels.writeandflush ("[SERVER]-" + incoming.remoteaddress () +"Leave \ n");A closed Channel is automatically removed from Channelgroup,So there are no need to do "Channels.remove (Ctx.channel ());"}@OverrideProtectedvoidChannelRead0(Channelhandlercontext CTX, String s)Throws Exception {(4) Channel incoming = Ctx.channel ();for (Channel channel:channels) {if (Channel! = incoming) {Channel.writeandflush ("[" + incoming.remoteaddress () +"]" + S +"\ n"); }else {Channel.writeandflush ("[You]" + S +"\ n"); } }}@OverridePublicvoidChannelactive(Channelhandlercontext CTX)Throws Exception {(5) Channel incoming = Ctx.channel (); System.out.println ("Simplechatclient:" +incoming.remoteaddress () +"Online");}@OverridePublicvoid channelinactive ( Channelhandlercontext ctx) throws Exception {//(6) Channel incoming = Ctx.channel (); System.out.println ( "simplechatclient:" +incoming.remoteaddress () +  "drop Line");}  @Override public void exceptioncaught//(7) Channel incoming = Ctx.channel (); System.out.println ( "simplechatclient:" +incoming.remoteaddress () + //when an exception occurs, close the connection cause.printstacktrace (); Ctx.close ();}      
    1. Simplechatserverhandler inherits from Simplechannelinboundhandler, this class implements the Channelinboundhandler interface, Channelinboundhandler Provides a number of interface methods for event handling, and then you can override these methods. Now it is only necessary to inherit the Simplechannelinboundhandler class instead of implementing the interface method yourself.

    2. Overrides the Handleradded () event handling method. Whenever a new client connection is received from the server, the client's channel is deposited in the Channelgroup list and the other client channel in the notification list

    3. Overrides the Handlerremoved () event handling method. Whenever a client disconnect is received from the server, the client's channel is automatically removed from the Channelgroup list and the other client channel in the list is notified

    4. Overrides the ChannelRead0 () event handling method. Forwards information to the Channel of other clients whenever the client writes information from the server. If you are using the Netty 5.x version, you need to rename channelRead0 () to Messagereceived ()

    5. Overrides the Channelactive () event handling method. Service-side monitor hears client activity

    6. Overrides the Channelinactive () event handling method. Service-side supervisor hears client inactive

    7. The Exceptioncaught () event handling method is called when a Throwable object occurs, that is, when Netty due to an IO error or the exception that is thrown by the processor when the event is handled. In most cases, the caught exception should be recorded and the associated channel closed. However, this approach can be handled differently when encountering different exceptions, such as a response message that you might want to send an error code before closing the connection.

Simplechatserverinitializer.java

Simplechatserverinitializer is used to add multiple processing classes to channelpipeline, including encoding, decoding, Simplechatserverhandler, and so on.

PublicClassSimplechatserverinitializerExtendschannelinitializer<socketchannel> {@Overridepublic void initchannel (socketchannel ch)  Throws Exception {Channelpipeline pipeline = Ch.pipeline (); Pipeline.addlast ( "Framer", Span class= "Hljs-keyword" >new delimiterbasedframedecoder (8192, Delimiters.lineDelimiter ())); Pipeline.addlast ( "decoder", new Stringdecoder ()); Pipeline.addlast ( "encoder", new Stringencoder ()); Pipeline.addlast ( "handler", new Simplechatserverhandler ()); System.out.println ( "simplechatclient:" +ch.remoteaddress () + "Connected"); }} 
Simplechatserver.java

Write a main () method to start the server.

PublicClassSimplechatserver {Privateint port;PublicSimplechatserver (int port) {This.port = port; }PublicvoidRun) throws Exception {Eventloopgroup Bossgroup =New Nioeventloopgroup ();(1) Eventloopgroup Workergroup =New Nioeventloopgroup ();try {serverbootstrap b =New Serverbootstrap ();(2) B.Group (Bossgroup, Workergroup). Channel (Nioserversocketchannel.class)(3). Childhandler (New Simplechatserverinitializer ())(4). Option (Channeloption.so_backlog,128)(5). Childoption (Channeloption.so_keepalive,true);(6) System.Out.println ("Simplechatserver started");Bind the port, start receiving incoming connections channelfuture f = b.bind (port). sync ();(7)Wait for the server socket to close.//in this example, this will not happen, but you can gracefully shut down your server. F.channel (). Closefuture (). sync (); } finally {workergroup.shutdowngracefully (); bossgroup.shutdowngracefully (); System. out.println ( "simplechatserver off");}} public static void main (string[] args) throws Exception {int port; if (Args.length > 0) {port = Integer.parseint (Args[0]); } else {port = 8080;} new simplechatserver (Port). Run ();}         
  1. Nioeventloopgroup is a multithreaded event circulator used to handle I/O operations, Netty provides many different implementations of Eventloopgroup to handle different transports. In this example we have implemented a service-side application, so there will be 2 nioeventloopgroup to be used. The first one is often called the ' boss ', which is used to receive incoming connections. The second is often called ' worker ', which is used to handle the connection that has been received, and once the ' boss ' receives the connection, it registers the connection information with the ' worker '. How to know how many threads have been used, how to map to the channel that has been created, depends on the implementation of Eventloopgroup, and can be configured by constructors to configure their relationships.

  2. Serverbootstrap is a secondary startup class that initiates the NIO service. You can use the Channel directly in this service, but this can be a complex process, and in many cases you do not need to do so.

  3. Here we specify the use of the Nioserversocketchannel class to illustrate how a new Channel receives incoming connections.

  4. The event handler class here is often used to handle a recent Channel that has been received. Simplechatserverinitializer inherited from Channelinitializer is a special processing class whose purpose is to help users configure a new Channel. Perhaps you want to implement your network program by adding some processing classes like Simplechatserverhandler to configure a new Channel or its corresponding channelpipeline. When your program becomes complex, you might add more processing classes to pipline, and then extract those anonymous classes onto the topmost class.

  5. You can set the configuration parameters specified here for the Channel implementation. We are writing a TCP/IP server, so we are allowed to set the socket parameter options such as Tcpnodelay and keepAlive. Please refer to the channeloption and detailed channelconfig implementation of the interface documentation so that you can have a general understanding of channeloption.

  6. Option () is provided to Nioserversocketchannel to receive incoming connections. Childoption () is provided to the connection received by the parent pipe Serverchannel, which is also nioserversocketchannel in this case.

  7. We continue, and all that is left is to bind the port and start the service. Here we bind the machine to the 8080 ports on all the machine cards. Of course now you can call the bind () method multiple times (based on different binding addresses).

Congratulations! You have completed the Netty Chat Service-based program.

Client Simplechatclienthandler.java

The client's processing class is relatively simple, just to print out the read information

public class SimpleChatClientHandler extends SimpleChannelInboundHandler<String> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {System.out.println(s);}}
Simplechatclientinitializer.java

Similar to the service side

PublicClassSimplechatclientinitializerExtendschannelinitializer<socketchannel> { @Override public void initchannel(Socketchannel ch) throws Exception { Channelpipeline pipeline = Ch.pipeline (); Pipeline.addlast ("Framer", new Delimiterbasedframedecoder (8192, Delimiters.linedelimiter ())); Pipeline.addlast ("Decoder", new Stringdecoder ()); Pipeline.addlast ("encoder", new Stringencoder ()); Pipeline.addlast ("Handler", new Simplechatclienthandler ());}}        
Simplechatclient.java

Write a main () method to start the client.

PublicClasssimplechatclient {PublicStaticvoidMainString[] args) throws exception{New Simplechatclient ("LocalHost",8080). Run (); }Private final String host;Private finalint port;PublicSimplechatclient (String Host,int port) {This.host = host;This.port = port; }PublicvoidRun) throws exception{EventloopgroupGroup =New Nioeventloopgroup ();try {Bootstrap Bootstrap = new Bootstrap ().  Group (Group). Channel (Niosocketchannel.class). Handler (new Simplechatclientinitializer ()); Channel channel = Bootstrap.connect (host, port). Sync (). Channel (); BufferedReader in = new BufferedReader (new InputStreamReader (System.  in)); while (true) {Channel.writeandflush (in.readline () + "\ r \ n");}} catch (Exception e) {e.printstacktrace ();} finally { group.shutdowngracefully ();            }}}} 
Run effect

Run Simplechatserver First, then run multiple simplechatclient, console input text continue testing

Source

See Https://github.com/waylau/netty-4-user-guide-demos

Netty Realization Chat function

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.