Netty is a simple example of communication between the client and the server.

Source: Internet
Author: User

Netty is a simple example of communication between the client and the server.

Netty is based on NIO, and Netty provides high-level abstraction on NIO.

In Netty, the Accept connection can be processed by a separate thread pool, and read/write operations are processed by another thread pool.

The same thread pool can also be used for Accept connections and read/write operations. The request processing logic can be processed either by a separate thread pool or by a read/write thread. Every thread in the thread pool is a NIO thread. The user can assemble according to the actual situation to construct a concurrency model meeting the system requirements.

Netty provides built-in common codecs, including row codecs [one request per row], prefix length codecs [the first N Bytes define the length of the request in bytes], replaying decoder [Recording the status of half-packet messages], HTTP codecs, WebSocket message codecs, etc.

Netty provides some column lifecycle callback interfaces. When a complete request arrives, when a connection is closed, the user will receive a callback event when a connection is established, then perform logical processing.

Netty can manage multiple ports at the same time and can use the NIO client model, which is necessary for the RPC service.

Netty can process TCP Socket and UDP Socket.

In the process of reading and writing messages, ByteBuffer needs to be used in large quantities. Netty optimizes and abstracts ByteBuffer in terms of performance and ease of use.

Code:

Server:

Package com. kinson. netty. server; import io. netty. bootstrap. serverBootstrap; import io. netty. channel. channel; import io. netty. channel. channelOption; import io. netty. channel. eventLoopGroup; import io. netty. channel. nio. nioEventLoopGroup; import io. netty. channel. socket. nio. nioServerSocketChannel;/*** descripiton: Server ** @ author: www.iknowba.cn * @ date: 2018/3/23 * @ time: * @ modifier: * @ since: */public class NettyServer {/*** port */private int port; public NettyServer (int port) {this. port = port;} public void run () {// EventLoopGroup is a multithreaded event Cycler used to handle IO operations // receives the client connection thread EventLoopGroup bossGroup = new NioEventLoopGroup (); // process client I/o events, task tasks, and listener task Group EventLoopGroup workerGroup = new NioEventLoopGroup (); // ServerBootstrap bootstrap = new ServerBootstrap (); bootstrap. group (bossGroup, workerGroup); // configure Channel bootstrap. channel (NioServerSocketChannel. class); bootstrap. childHandler (new ServerIniterHandler (); // BACKLOG is used to construct the ServerSocket object of the server socket. // It indicates that when the server request processing thread is full, it is used to temporarily store the maximum length of the bootstrap queue for requests that have completed three handshakes. option (ChannelOption. SO_BACKLOG, 1024); // whether to enable the heartbeat persistence mechanism bootstrap. childOption (ChannelOption. SO_KEEPALIVE, true); try {// bind the service port to listen to the Channel channel = bootstrap. bind (port ). sync (). channel (); System. out. println ("server run in port" + port); // The server closes the listener/* channel. closeFuture (). how sync () actually works: channel. closeFuture () does not perform any operation, but simply returns the closeFuture object in the channel object. For each Channel object, there will be a unique CloseFuture, which indicates the closed Future and all the channels that are executed. closeFuture (). sync () is the executed CloseFuturn sync method. As you can see from the above explanation, this step will block the current thread on CloseFuture */channel. closeFuture (). sync ();} catch (InterruptedException e) {e. printStackTrace ();} finally {// close the event stream group bossGroup. shutdownGracefully (); workerGroup. shutdownGracefully () ;}} public static void main (String [] args) {new NettyServer (8899 ). run ();}}

Service logic processing:

Package com. kinson. netty. server; import io. netty. channel. channel; import io. netty. channel. channelHandlerContext; import io. netty. channel. simpleChannelInboundHandler; import io. netty. channel. group. channelGroup; import io. netty. channel. group. defaultChannelGroup; import io. netty. util. concurrent. globalEventExecutor;/*** descripiton: server processing logic ** @ author: www.iknowba.cn * @ date: 2018/3/23 * @ time: * @ m Odifier: * @ since: */public class ServerHandler extends SimpleChannelInboundHandler <String> {/*** all active users */public static final ChannelGroup group = new DefaultChannelGroup (GlobalEventExecutor. INSTANCE);/*** read the message channel ** @ param context * @ param s * @ throws Exception */@ Override protected void channelRead0 (ChannelHandlerContext context, String s) throws Exception {Channel channel = context. cha Nnel (); // when a user sends a message to another user, send the message for (Channel ch: group) {if (ch = channel) {ch. writeAndFlush ("[you]:" + s + "\ n");} else {ch. writeAndFlush ("[" + channel. remoteAddress () + "]:" + s + "\ n") ;}} System. out. println ("[" + channel. remoteAddress () + "]:" + s + "\ n ");} /*** process the newly added Message Channel ** @ param ctx * @ throws Exception */@ Override public void handlerAdded (ChannelHandlerContext ctx) throws Exc Eption {Channel channel = ctx. channel (); for (Channel ch: group) {if (ch = channel) {ch. writeAndFlush ("[" + channel. remoteAddress () + "] coming");} group. add (channel);}/*** process and exit the Message channel ** @ param ctx * @ throws Exception */@ Override public void handlerRemoved (ChannelHandlerContext ctx) throws Exception {Channel channel = ctx. channel (); for (Channel ch: group) {if (ch = channel) {ch. wr IteAndFlush ("[" + channel. remoteAddress () + "] leaving");} group. remove (channel);}/*** send a message when a connection is established ** @ param ctx * @ throws Exception */@ Override public void channelActive (ChannelHandlerContext ctx) throws Exception {Channel channel = ctx. channel (); boolean active = channel. isActive (); if (active) {System. out. println ("[" + channel. remoteAddress () + "] is online");} else {System. out. print Ln ("[" + channel. remoteAddress () + "] is offline");} ctx. writeAndFlush ("[server]: welcome");}/*** send a message upon exit ** @ param ctx * @ throws Exception */@ Override public void channelInactive (ChannelHandlerContext ctx) throws Exception {Channel channel = ctx. channel (); if (! Channel. isActive () {System. out. println ("[" + channel. remoteAddress () + "] is offline");} else {System. out. println ("[" + channel. remoteAddress () + "] is online ");}} /*** Exception capture *** @ param ctx * @ param e * @ throws Exception */@ Override public void exceptionCaught (ChannelHandlerContext ctx, Throwable e) throws Exception {Channel channel = ctx. channel (); System. out. println ("[" + channel. remoteAddress () + "] leave the room"); ctx. close (). sync ();}}

Server processor registration:

Package com. kinson. netty. server; import io. netty. channel. channelInitializer; import io. netty. channel. channelPipeline; import io. netty. channel. socket. socketChannel; import io. netty. handler. codec. string. stringDecoder; import io. netty. handler. codec. string. stringEncoder;/*** descripiton: Server initialization ** @ author: www.iknowba.cn * @ date: 2018/3/23 * @ time: * @ modifier: * @ since: */public class ServerIniterHandler extends ChannelInitializer <SocketChannel >{@ Override protected void initChannel (SocketChannel socketChannel) throws Exception {// pipeline registration handler ChannelPipeline pipeline = socketChannel. pipeline (); // The encoding channel for processing pipeline. addLast ("decode", new StringDecoder (); // transcoding channel processing pipeline. addLast ("encode", new StringEncoder (); // processes pipeline through the chat service channel. addLast ("chat", new ServerHandler ());}}

Client:

Package com. kinson. netty. client; import io. netty. bootstrap. bootstrap; import io. netty. channel. channel; import io. netty. channel. eventLoopGroup; import io. netty. channel. nio. nioEventLoopGroup; import io. netty. channel. socket. nio. nioSocketChannel; import org. apache. commons. lang3.StringUtils; import java. io. bufferedReader; import java. io. IOException; import java. io. inputStreamReader;/*** descripiton: client ** @ author: www.iknowba.cn * @ date: 88/3/23 * @ time: 16:40 * @ modifier: * @ since: */public class NettyClient {private String ip; private int port; private boolean stop = false; public NettyClient (String ip, int port) {this. ip = ip; this. port = port;} public void run () throws IOException {// set EventLoopGroup workerGroup = new NioEventLoopGroup (); // start the annotation class Bootstrap bootstrap = new Bootstrap (); bootstrap. group (workerGroup); // specifies the NIO transmission channel bootstrap used. channel (NioSocketChannel. class); // specifies the client initialization process bootstrap. handler (new ClientIniterHandler (); try {// Connection Service Channel = bootstrap. connect (ip, port ). sync (). channel (); while (true) {// content sent to the server BufferedReader reader = new BufferedReader (new InputStreamReader (System. in); String content = reader. readLine (); if (StringUtils. isNotEmpty (content) {if (StringUtils. equalsIgnoreCase (content, "q") {System. exit (1);} channel. writeAndFlush (content) ;}} catch (InterruptedException e) {e. printStackTrace (); System. exit (1);} finally {workerGroup. shutdownGracefully () ;}} public static void main (String [] args) throws Exception {new NettyClient ("127.0.0.1", 8899 ). run ();}}

Client logic processing:

Package com. kinson. netty. client; import io. netty. channel. channelHandlerContext; import io. netty. channel. simpleChannelInboundHandler;/*** descripiton: client logic processing ** @ author: www.iknowba.cn * @ date: 88/3/23 * @ time: * @ modifier: * @ since: */public class ClientHandler extends SimpleChannelInboundHandler <String >{@ Override protected void channelRead0 (ChannelHandlerContext ctx, String s) throws Exception {// print the sending data System of the server. out. println (s );}}

Client processor registration:

Package com. kinson. netty. client; import io. netty. channel. channelInitializer; import io. netty. channel. channelPipeline; import io. netty. channel. socket. socketChannel; import io. netty. handler. codec. http. httpClientCodec; import io. netty. handler. codec. string. stringDecoder; import io. netty. handler. codec. string. stringEncoder;/*** descripiton: Initialize client processing ** @ author: www.iknowba.cn * @ date: 88/3/23 * @ time: * @ modifier: * @ since: */public class ClientIniterHandler extends ChannelInitializer <SocketChannel >{@ Override protected void initChannel (SocketChannel socketChannel) throws Exception {// register the channel ChannelPipeline pipeline = socketChannel. pipeline (); pipeline. addLast ("decoder", new StringDecoder (); pipeline. addLast ("encoder", new StringEncoder (); pipeline. addLast ("http", new HttpClientCodec (); pipeline. addLast ("chat", new ClientHandler ());}}

Start the server before testing...

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.