Create a Netty learning client and a netty Client

Source: Internet
Author: User

Create a Netty learning client and a netty Client
I. Client development sequence diagram

  

Image Source: Netty authoritative guide (2nd)

2. Netty client development steps

To use Netty for client development, follow these steps:

1. User threads create Bootstrap
Bootstrap b = new Bootstrap();

Bootstrap is a tool for creating a Socket client. You can use APIs to set parameters related to creating a client and initiate client connections asynchronously.

2. Create a Reactor thread group NioEventLoopGroup that processes client connections and IO read/write
EventLoopGroup group = new NioEventLoopGroup();
3. Create a NioSocketChannel for client connection through the Channel factory of Bootstrap and the Channel type specified by the user
b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)

The NioSocketChannel here is similar to the SocketChannel provided by Java NIO.

4. Create the default channel Handler pipeline
b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>()  {       @Override       public void initChannel(SocketChannel ch) throws Exception       {         ch.pipeline().addLast(new HelloClientHandler());        }  });

Used to schedule and execute network events.

5. Initiate a TCP connection Asynchronously
// Initiate the asynchronous connection operation ChannelFuture f = B. connect (host, port). sync ();

There are three results after SocketChannel performs the connect () operation:

  • If the connection is successful, true is displayed;
  • There is no connection at the moment, the server does not return an ACK response, the connection result is uncertain, and false is returned. In this case, the selectionKey in the NioSocketChannel needs to be set to OP_CONNECT to listen for the connection results;
  • An I/O exception is thrown directly when the connection fails.
6. the multiplexing round-robin Channel in I/O to process the connection result 7. If the connection is successful, set the Future result and send the connection success event, trigger ChannelPipeline execution 8. The ChannelPipeline scheduling Execution System and the user's ChannelHandler execute business logic 3. Netty client development sample code

Requirement: implement on the client side, connect to the server side, and send hello Netty to the server side. (Note: the netty used in this code is the netty-all-5.0.0.Alpha1-sources.jar Version)

For server-side code, refer to "create server-side with Netty learning ".

Client code:

Import io. netty. bootstrap. bootstrap; 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. nioSocketChannel; public class HelloClient {public void connect (int port, String host) throws Exception {// configure the client NIO thread group EventLoopGroup group = new NioEventLoopGroup (); try {Bootstrap B = new Bootstrap (); B. group (group ). channel (NioSocketChannel. class ). option (ChannelOption. TCP_NODELAY, true ). handler (new ChannelInitializer <SocketChannel> () {@ Override public void initChannel (SocketChannel ch) throws Exception {ch. pipeline (). addLast (new HelloClientHandler () ;}}); // initiate an asynchronous connection operation ChannelFuture f = B. connect (host, port ). sync (); // wait until the client link is closed. channel (). closeFuture (). sync ();} finally {group. shutdownGracefully () ;}} public static void main (String [] args) throws Exception {int port = 8080; new HelloClient (). connect (port, "127.0.0.1 ");}}
import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerAdapter;import io.netty.channel.ChannelHandlerContext;public class HelloClientHandler  extends ChannelHandlerAdapter{    private final ByteBuf message;        public HelloClientHandler()    {        byte[] req="hello Netty".getBytes();        message=Unpooled.buffer(req.length);        message.writeBytes(req);    }    @Override    public void channelActive(ChannelHandlerContext ctx) throws Exception    {        ctx.writeAndFlush(message);    }        @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception    {        ctx.close();    }}

Program running result:

  

Iv. References

1. Netty authoritative guide

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.