Netty Programming HelloWorld
adopt Netty Of HelloWorld And NIO Of HelloWord Contrast
Analyze the complexity of these two developments , To prove Netty The meaning of
Given the NIO, Why do we still need Netty
review NIO Steps for 【 Click here 】:
You can find , use NIO Programming is very complicated , Use Netty Programming can simplify development .
1
Netty Server side development
public class TimeServer { public void bind(int port) { // Configure the server side NIO Thread group //NioEventLoopGroup It's a thread group , Contains a set of NIO Threads , Dealing with network events , It's actually Reactor Thread group try (EventLoopGroup bossLoopGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup()){ //netty Used to start NIO Server startup class , The aim is to reduce NIO The complexity of development ServerBootstrap bootstrap = new ServerBootstrap(); // Function like NIO Medium ServerSocketChannel bootstrap.group(bossLoopGroup, workerGroup).channel(NioServerSocketChannel.class) // To configure NioServerSocketChannel Parameters of .option(ChannelOption.SO_BACKLOG, 1024) // Binding event handling class ChildChannelHandler .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new TimeServerHandler()); } }); // Binding port , Wait for the binding operation to complete ChannelFuture channelFuture = bootstrap.bind(port).sync(); // Wait for the server listening port to close channelFuture.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { int port = 8888; new TimeServer().bind(port); } }
Server side processing class ChildChannelHandler The specific processing logic is as follows :
public class TimeServerHandler extends ChannelHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { // similar NIO Medium ByteBuffer ByteBuf buf = (ByteBuf) msg; // Gets the number of bytes read in the buffer byte[] req = new byte[buf.readableBytes()]; // The bytes in the buffer are copied to the byte array buf.readBytes(req); String body = new String(req); System.out.println(" Input received :" + body); ByteBuf response = Unpooled.copiedBuffer((" current time :" + new Date()).getBytes()); // It's not sending messages directly to SocketChannel in , Just send the message to the buffer array , adopt flush Method to send a message to SocketChannel ctx.write(response); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { // Write messages from the message sending queue to SocketChannel in , Send to the other party // Prevent frequent wakeups Selector Send message ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // An abnormal shutdown occurred ChannelHandlerContext And so on ctx.close(); } }
2
Netty Client development
public class TimeClient { public void connect(int port, String host) { try (EventLoopGroup eventLoopGroup = new NioEventLoopGroup()){ Bootstrap bootstrap = new Bootstrap(); bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new TimeClientHandler()); } }); // Asynchronous link operation ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); // Wait for the client channelFuture.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { int port = 8888; new TimeClient().connect(port, "127.0.0.1"); } }
Client processing class TimeClientHandler The specific processing logic is as follows :
public class TimeClientHandler extends ChannelHandlerAdapter { private final ByteBuf firstMessage; public TimeClientHandler() { byte[] req = "hello world".getBytes(); firstMessage = Unpooled.buffer(req.length); firstMessage.writeBytes(req); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(firstMessage); } /** * Read and print messages * @param ctx * @param msg * @throws Exception */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; byte[] resp = new byte[buf.readableBytes()]; buf.readBytes(resp); String body = new String(resp); System.out.println(body); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); } }
summary
You can find , Compared with using it directly NIO Development ,netty The code is more concise , Less difficult to develop , Better scalability .
This official account will be introduced later Netty How to deal with TCP Sticking and unpacking and so on , Stay tuned
This article is from WeChat official account. - The snail flying in the fallen leaves (A_GallopingSnail) , author : The supernatural snail
The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the yunjia_community@tencent.com Delete .
Original publication time : 2018-09-07
Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .