Netty初识之DiscardServer

本是古典 何须时尚 2022-05-16 07:29 305阅读 0赞

Netty

Netty项目是为了快速开发可维护的高性能高可扩展性协议服务器和客户端而努力提供异步事件驱动的网络应用程序框架和工具。换句话说,Netty是一个NIO客户端服务器框架,可以快速轻松地开发诸如协议服务器和客户端之类的网络应用程序。它大大简化了网络编程流程,如TCP和UDP套接字服务器开发。

Tomcat和Netty的比较

Netty和Tomcat最大的区别就在于通信协议,Tomcat是基于Http协议的,他的实质是一个基于http协议的web容器,但是Netty不一样,他能通过编程自定义各种协议,因为netty能够通过codec自己来编码/解码字节流,完成类似redis访问的功能,这就是netty和tomcat最大的不同

Netty特点:

  1. 并发高
  2. 传输快
  3. 封装好

70

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.sengen</groupId>
  6. <artifactId>nettydemos</artifactId>
  7. <version>1.0-SNAPSHOT</version>
  8. <name>nettydemos</name>
  9. <!-- FIXME change it to the project's website -->
  10. <url>http://www.example.com</url>
  11. <properties>
  12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  13. <maven.compiler.source>1.8</maven.compiler.source>
  14. <maven.compiler.target>1.8</maven.compiler.target>
  15. </properties>
  16. <dependencies>
  17. <dependency>
  18. <groupId>junit</groupId>
  19. <artifactId>junit</artifactId>
  20. <version>4.11</version>
  21. <scope>test</scope>
  22. </dependency>
  23. <dependency>
  24. <groupId>io.netty</groupId>
  25. <artifactId>netty-all</artifactId>
  26. <version>4.0.32.Final</version>
  27. </dependency>
  28. </dependencies>
  29. <build>
  30. <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
  31. <plugins>
  32. <plugin>
  33. <artifactId>maven-clean-plugin</artifactId>
  34. <version>3.0.0</version>
  35. </plugin>
  36. <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
  37. <plugin>
  38. <artifactId>maven-resources-plugin</artifactId>
  39. <version>3.0.2</version>
  40. </plugin>
  41. <plugin>
  42. <artifactId>maven-compiler-plugin</artifactId>
  43. <version>3.7.0</version>
  44. </plugin>
  45. <plugin>
  46. <artifactId>maven-surefire-plugin</artifactId>
  47. <version>2.20.1</version>
  48. </plugin>
  49. <plugin>
  50. <artifactId>maven-jar-plugin</artifactId>
  51. <version>3.0.2</version>
  52. </plugin>
  53. <plugin>
  54. <artifactId>maven-install-plugin</artifactId>
  55. <version>2.5.2</version>
  56. </plugin>
  57. <plugin>
  58. <artifactId>maven-deploy-plugin</artifactId>
  59. <version>2.8.2</version>
  60. </plugin>
  61. </plugins>
  62. </pluginManagement>
  63. </build>
  64. </project>
  65. package com.sengen.netty_beginner;
  66. import io.netty.bootstrap.ServerBootstrap;
  67. import io.netty.channel.ChannelFuture;
  68. import io.netty.channel.ChannelInitializer;
  69. import io.netty.channel.ChannelOption;
  70. import io.netty.channel.EventLoopGroup;
  71. import io.netty.channel.nio.NioEventLoopGroup;
  72. import io.netty.channel.socket.SocketChannel;
  73. import io.netty.channel.socket.nio.NioServerSocketChannel;
  74. /**
  75. * Created by Administrator on 2018/8/17.
  76. * 描述:DiscardServer 启动类
  77. * @author Young
  78. * @create 2018-08-17 14:35
  79. */
  80. public class DiscardServer {
  81. private int port;
  82. public DiscardServer(int port) {
  83. this.port = port;
  84. }
  85. public static void main(String[] args) {
  86. int port;
  87. if(args.length>0){
  88. port = Integer.valueOf(args[1]);
  89. }else {
  90. port = 8080;
  91. }
  92. System.out.println("准备启动中.........");
  93. new DiscardServer(port).run();
  94. //好像永远都执行不到回家的代码......
  95. System.out.println("跑完了....肥噶!");
  96. }
  97. private void run() {
  98. /**NioEventLoopGroup是一个处理I/O操作的多线程事件循环.Netty为不同类型的传输提供了各种EventLoopGroup实现.在这个例子中,我们正在实现一个
  99. * 服务器端应用程序,因此将使用两个NioEventLoopGroup.
  100. * 第一个 通常称为老板,接收传入的连接;
  101. * 第二个 通常称为工人,一旦老板接收连接并将接受的连接注册给工作人员,就处理接收的连接的流量.
  102. * 使用多少线程以及他们如何映射到创建的通道取决于EventLoopGroup实现,甚至可以通过构造函数进行配置.
  103. */
  104. EventLoopGroup bossGroup = new NioEventLoopGroup();
  105. EventLoopGroup workerGroup = new NioEventLoopGroup();
  106. try{
  107. /**
  108. * ServerBootstrap是一个帮助类,用于设置服务器.可以直接使用Channel设置服务器.但是一般情况都不这样做..
  109. **/
  110. ServerBootstrap sb = new ServerBootstrap();
  111. sb.group(bossGroup,workerGroup)
  112. /**
  113. * 在这里,我们指定使用NioServerSocketChannel类来实例化一个新的Channel来接收传入的连接.
  114. * (每个客户端连接服务端,我们都为他们创建一个channel,那么这个channel对于面向对象的我们来说就是一个类,我们统一对于我们接收
  115. * 到的连接都初始化为:NioServerSocketChannel)
  116. */
  117. .channel(NioServerSocketChannel.class)
  118. /**
  119. * 这里指定的处理程序将始终由新接收的Channel进行评估.ChannelInitializer是一个特殊的处理程序,旨在帮助用户配置新的Channel.
  120. * 若想通过添加一些处理程序(如DiscardServerHandler)来配置新Channel的ChannelPipeline来实现网络应用程序.
  121. * 随着应用程序的复杂化,可能在管道中添加更多的处理程序..(其实这就是需要自己重新实现包含自己处理逻辑的Channel.
  122. * 类似于DiscardServerHandler,继承ChannelInboundHandlerAdapter一样)
  123. * */
  124. .childHandler(new ChannelInitializer<SocketChannel>() {
  125. @Override
  126. protected void initChannel(SocketChannel socketChannel) throws Exception {
  127. socketChannel.pipeline().addLast(new DiscardServerHandler());
  128. }
  129. })
  130. /**
  131. * 设置特定于Channel实现的参数.正在编写一个TCP/IP服务器.因此可以设置套接字选项.如tcpNoDelay和keepAlive
  132. *
  133. * option()和childOption()方法.
  134. * option()用于接收传入连接的NioServerChannel.
  135. * childOption()用于在这种情况下由父级ServerChannel接收的通道,即NioServerSocketChannel.
  136. * 个人认为:前者用于配置父级Channel,后者配置自定义的子集Channel.
  137. */
  138. .option(ChannelOption.SO_BACKLOG,128)
  139. .childOption(ChannelOption.SO_KEEPALIVE,true);
  140. ChannelFuture future = sb.bind(port).sync();
  141. future.channel().closeFuture().sync();
  142. }catch(Exception e){
  143. System.out.println("有异常,快跑...........");
  144. }finally{
  145. bossGroup.shutdownGracefully();
  146. workerGroup.shutdownGracefully();
  147. }
  148. }
  149. }
  150. package com.sengen.netty_beginner;
  151. import io.netty.buffer.ByteBuf;
  152. import io.netty.channel.Channel;
  153. import io.netty.channel.ChannelHandlerContext;
  154. import io.netty.channel.ChannelInboundHandlerAdapter;
  155. import io.netty.util.ReferenceCountUtil;
  156. import java.net.SocketAddress;
  157. /**
  158. * Created by Administrator on 2018/8/17.
  159. * 描述:手动完成比hello world还简单的程序
  160. * @author Young
  161. * @create 2018-08-17 14:29
  162. */
  163. public class DiscardServerHandler extends ChannelInboundHandlerAdapter {
  164. @Override
  165. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  166. //将Object强转成ByteBuf(引用计数对象)
  167. // ((ByteBuf)msg).release();
  168. ByteBuf in = (ByteBuf) msg;
  169. try {
  170. while (in.isReadable()) {
  171. Channel channel = ctx.channel();
  172. SocketAddress socketAddress = channel.remoteAddress();
  173. System.out.println(socketAddress+"连接了你");
  174. System.out.print((char) in.readByte());
  175. System.out.flush();
  176. }
  177. } finally {
  178. ReferenceCountUtil.release(msg);
  179. }
  180. }
  181. @Override
  182. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  183. // cause.printStackTrace();
  184. System.out.println(ctx.channel().remoteAddress()+"强迫关闭了连接");
  185. System.out.println("跑完了......肥噶!");
  186. ctx.close();
  187. }
  188. }

控制台启动main方法…网页和cmd都可以访问…..localhost:8080…..localhost改成ip通用的…

我感觉我要把我的github用起来了…贴代码不方便了.

发表评论

表情:
评论列表 (有 0 条评论,305人围观)

还没有评论,来说两句吧...

相关阅读

    相关 UML

                初识UML是在跟室友聊天的时候谈到了到活动图,室友问我,你对活动图了解吗?      因为大二的时候在社团里面也任过职,所以对做活动需要个什么流程之类

    相关 Netty

    Netty是什么? Netty是由[JBOSS][]提供的一个java开源框架。Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络

    相关 jvm

    一、jvm体系结构: ![这里写图片描述][Image 1] 二、.class文件: 这个众所周知,这里就不废话了,.class文件就是javac编译之后产生的文件 三