Introduction to netty development

Black hole code 2021-01-14 16:27:59
introduction netty development


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 】:

  1. establish ServerSocketChannel, Configured as non blocking
  2. Binding monitoring , To configure TCP Parameters
  3. Create an independent IO Threads , User polling multiplexer Selector
  4. establish Selector, take ServerSocketChannel Sign up to Selector On , monitor ACCEPT event
  5. start-up IO Threads , Execute... In the body of the loop Selector.select() Method
  6. Polling to ready Channel, Judge it , If it is ACCEPT state , The description is client access , call ServerSocketChannel.accept() Receive new clients
  7. Set the new access client's SocketChannel Non blocking , Set up TCP Parameters
  8. take SocketChannel Sign up to Selector, monitor READ operation
  9. If the polling event is READ, explain SocketChannel There are new packets ready , structure ByteBuffer object , Read packets
  10. If polling comes to WRITE event , It means that there is still data to be sent , Need to continue sending

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 .

版权声明
本文为[Black hole code]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210114162621259x.html

  1. To what extent can I go out to work?
  2. Java 使用拦截器无限转发/重定向无限循环/重定向次数过多报错(StackOverflowError) 解决方案
  3. Implementation of rocketmq message sending based on JMeter
  4. How to choose the ticket grabbing app in the Spring Festival? We have measured
  5. Implementation of rocketmq message sending based on JMeter
  6. My programmer's Road: self study java
  7. My programmer's Road: self study java
  8. All in one, one article talks about the use of virtual machine VirtualBox and Linux
  9. All in one, one article talks about the use of virtual machine VirtualBox and Linux
  10. Java 使用拦截器无限转发/重定向无限循环/重定向次数过多报错(StackOverflowError) 解决方案
  11. [Java training project] Java ID number recognition system
  12. How does serverless deal with the resource supply demand of k8s in the offline scenario
  13. Detailed explanation of HBase basic principle
  14. Explain the function of thread pool and how to use it in Java
  15. Kubernetes official java client 8: fluent style
  16. 010_MySQL
  17. Vibrant special purchases for the Spring Festival tiktok section, hundreds of good things to make the year more rich flavor.
  18. 010_MySQL
  19. Of the 4 million docker images, 51% have high-risk vulnerabilities
  20. Rocketmq CPP client visual studio 2019 compilation
  21. Rocketmq CPP client visual studio 2019 compilation
  22. Usage of data custom attribute in jquery
  23. Common decompression in Linux
  24. Upload large files in Java
  25. Sentry (v20.12.1) k8s cloud native architecture exploration, sentry for JavaScript manual capture event basic usage
  26. Sentry (v20.12.1) k8s cloud native architecture exploration, sentry for JavaScript manual capture event basic usage
  27. Docker + MySQL Cluster + read / write separation + MYCAT Management + vertical sub database + load balancing
  28. Docker + MySQL Cluster + read / write separation + MYCAT Management + vertical sub database + load balancing
  29. Java use interceptor infinite forwarding / redirection infinite loop / redirection times too many error (stack overflow error) solution
  30. Java use interceptor infinite forwarding / redirection infinite loop / redirection times too many error (stack overflow error) solution
  31. 010_ MySQL
  32. 010_ MySQL
  33. Fast integration of imsdk and Huawei offline push
  34. 消息队列之RabbitMQ
  35. Rabbitmq of message queue
  36. 初学java进制转换方面补充学习
  37. Learn java base conversion supplementary learning
  38. 了解一下RPC,为何诞生RPC,和HTTP有什么不同?
  39. 了解一下RPC,为何诞生RPC,和HTTP有什么不同?
  40. 初学java进制转换方面补充学习
  41. Learn about RPC, why RPC was born, and what's the difference between RPC and HTTP?
  42. Learn about RPC, why RPC was born, and what's the difference between RPC and HTTP?
  43. Learn java base conversion supplementary learning
  44. JDBC测试连接数据库
  45. JDBC test connection database
  46. 大厂面试官竟然这么爱问Kafka,一连八个Kafka问题把我问蒙了?
  47. The interviewers of big factories love to ask Kafka so much. I'm blinded by eight Kafka questions in a row?
  48. 安卓开发和java开发有什么区别!2021年BATJ30套大厂Android经典高频面试题,面试必问
  49. Spring Security OAuth2.0認證授權四:分散式系統認證授權
  50. What's the difference between Android development and java development! 2021 batj30 Android classic high frequency interview questions
  51. Spring security oauth2.0 authentication and authorization 4: distributed system authentication and authorization
  52. Java微服务 vs Go微服务,究竟谁更强!?
  53. 大厂面试官竟然这么爱问Kafka,一连八个Kafka问题把我问蒙了?
  54. Who is stronger, Java microservice vs go microservice!?
  55. Java微服务 vs Go微服务,究竟谁更强!?
  56. The interviewers of big factories love to ask Kafka so much. I'm blinded by eight Kafka questions in a row?
  57. Who is stronger, Java microservice vs go microservice!?
  58. springboot异常处理之404
  59. Spring boot exception handling 404
  60. Spring Boot Security 国际化 多语言 i18n 趟过巨坑