Basic Netty tutorial-server Creation

Source: Internet
Author: User

Basic Netty tutorial-server Creation

Reading directory

  • I. server-side development sequence diagram
  • Ii. Netty server development steps
  • Iii. Sample Code for Netty server development
  • Iv. References
I. server-side development sequence diagram

  

Image Source: Netty authoritative guide (2nd)

Ii. Netty server development steps

To use Netty for server development, follow these steps:

1. Create a ServerBootstrap instance
ServerBootstrap b=new ServerBootstrap();

ServerBootstrap is a helper class for starting Netty servers. It provides a series of methods for setting server startup parameters.

2. Set and bind the Reactor Thread Pool
EventLoopGroup bossGruop = new NioEventLoopGroup (); // used by the server to accept the client connection EventLoopGroup workGroup = new NioEventLoopGroup (); // used to process network events

Netty's thread pool is EventLoopGroup, which is actually an array of EventLoop. EventLoop is responsible for processing all the channels registered to the Selector of the thread multiplexing, the Selector polling operation is driven by the bound EventLoop thread run method.

3. Set and bind the server-side Channel
b.group(bossGruop, workGroup).channel(NioServerSocketChannel.class)

Netty encapsulates native NIO class libraries. As the NIO server, you need to create a ServerSocketChannel. The corresponding implementation is NioServerSocketChannel.

4. Create and initialize ChannelPipeline during link Creation
b.group(bossGruop, workGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>()

ChannelPipeline is essentially a responsibility chain responsible for handling network events and managing and executing ChannelHandler. Network events flow in the form of event streams in ChannelPipeline. ChannelPipeline schedules the execution of ChannelHandler according to the Channel | Handler's execution policy. Typical network events include:

  • Link Registration
  • Link Activation
  • Link disconnected
  • Received request information
  • Request information received and processed
  • Send Response Message
  • Link exception
  • Custom events
5. Add and set ChannelHandler
b.group(bossGruop, workGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {   @Override   protected void initChannel(SocketChannel arg0) throws Exception   {    arg0.pipeline().addLast(new HelloServerHandler());                       } }).option(ChannelOption.SO_BACKLOG, 1024);

ChannelHandler is a custom and extended interface provided by Netty, such as message codec, heartbeat, security authentication, and TSL/SSL authentication.

6. Bind and start the listener window
ChannelFuture f=b.bind(port).sync();

After a series of initialization and detection work, the listener port is started and the ServerSocketChannel is registered to the Selector to listen for client connection.

7. Selector round robin

The Reactor thread NioEventLoop is responsible for scheduling and executing the Selector round robin operation, and selects the ready Channel set.

8. After polling to the ready Channel, the Reactor thread NioEventLoop executes the corresponding method of ChannelPipeline, and finally schedules and executes ChannelHandler.
public class HelloServerHandler extends ChannelHandlerAdapter
Iii. Sample Code for Netty server development

Requirement: server-side implementation. Each time a client is connected, the characters entered by the client are printed on the server console. (Note: the netty used in this code is the netty-all-5.0.0.Alpha1-sources.jar Version)

The server code is as follows:

Import io. netty. bootstrap. serverBootstrap; import io. netty. channel. channelFuture; import io. netty. channel. channelInitializer; import io. netty. channel. channelOption; import io. netty. channel. eventLoopGroup; import io. netty. channel. nio. nioEventLoopGroup; import io. netty. channel. socket. socketChannel; import io. netty. channel. socket. nio. nioServerSocketChannel; // Netty server side public class HelloServer {private int port; public HelloServer (int port) {super (); this. port = port;} private void bind () throws InterruptedException {EventLoopGroup bossGruop = new NioEventLoopGroup (); // used by the server to accept the client connection EventLoopGroup workGroup = new NioEventLoopGroup (); // for handling network events try {ServerBootstrap B = new ServerBootstrap (); B. group (bossGruop, workGroup ). channel (NioServerSocketChannel. class ). childHandler (new ChannelInitializer <SocketChannel> () {@ Override protected void initChannel (SocketChannel arg0) throws Exception {arg0.pipeline (). addLast (new HelloServerHandler ());}}). option (ChannelOption. SO_BACKLOG, 1024); // specifies the maximum number of connections queued for this set of interfaces. ChannelFuture f = B. bind (port ). sync (); f. channel (). closeFuture (). sync ();} finally {bossGruop. shutdownGracefully (); workGroup. shutdownGracefully () ;}} public static void main (String [] args) throws InterruptedException {new HelloServer (8080 ). bind ();}}
Import io. netty. buffer. byteBuf; import io. netty. channel. channelHandlerAdapter; import io. netty. channel. channelHandlerContext; // custom ChannelHandlerpublic class HelloServerHandler extends ChannelHandlerAdapter {@ Override public void channelActive (ChannelHandlerContext ctx) throws Exception {System. out. println ("the client is connected... ") ;}@ Override public void channelRead (ChannelHandlerContext ctx, Object msg) throws Exception {ByteBuf buf = (ByteBuf) msg; byte [] req = new byte [buf. readableBytes ()]; buf. readBytes (req); System. out. println ("message received by the server:" + new String (req) ;}@ Override public void channelReadComplete (ChannelHandlerContext ctx) throws Exception {ctx. flush () ;}@ Override public void exceptionCaught (ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx. close ();}}

Client: use telnet to simulate client input,

  

Press ctrl +] and enter the command send

  

Iv. References

1. Netty authoritative guide (Li linfeng) [Netty authoritative guide PDF full version with directory bookmarks + Source Code]

Use Spring annotations to implement Netty server-side UDP applications

Netty source code learning notes

Netty instance

Java NIO framework -- a simple example of Netty4

Netty details: click here
Netty: click here

This article permanently updates the link address:

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.