为什么80%的码农都做不了架构师?>>>   

这两天学习netty,记录一下。

netty 介绍不废话。

官方网站:http://netty.io/

使用netty高层次抽象的API,无需编写底层的NIO、或java7 的NIO.2 代码,并且完美兼容。

使用netty高层次抽象的API,完美融合并发编程中的futrue跟callback模式,编写出优雅且易维护,高性能的应用。

使用netty高层次抽象的API,可以实践传说中的SEDA,编写出号称支持高并发的应用。

使用netty高层次抽象的API,您再也不用为编写多线程应用难度而烦恼。

初初看,给我的感觉这样的,好好学习,天天向上。

传统Server端处理不同连接客户端的办法:

使用NIO之后:

实践Echo程序:

创建Maven工程。pom.xml需要的依赖。

<dependencies><dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.0.0.Final</version></dependency></dependencies>

EchoServer.java

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import java.net.InetSocketAddress;
import java.util.logging.Level;
import java.util.logging.Logger;/**** @author XzF*/
public class EchoServer
{private final int port;public EchoServer( int port ){this.port = port;}public void start() throws InterruptedException{EventLoopGroup group = new NioEventLoopGroup();try{ServerBootstrap bootstrap = new ServerBootstrap();bootstrap.group( group )//.channel( NioServerSocketChannel.class )//.localAddress( new InetSocketAddress( port ) )//.childHandler(new ChannelInitializer<SocketChannel>(){@Overrideprotected void initChannel( SocketChannel ch ) throws Exception{ch.pipeline().addLast( new EchoServerHandler() );}} //);ChannelFuture f = bootstrap.bind().sync();System.out.println(EchoServer.class.getName()+ " started and listen on " + f.channel().localAddress());f.channel().closeFuture().sync();}finally{group.shutdownGracefully().sync();}}public static void main( String[] args ){int port = 9999;if ( args.length == 1 ){port = Integer.parseInt( args[0] );}System.out.println( "Usage: . + EchoServer.class.getSimpleName() +. <port> : " + port );try{new EchoServer( port ).start();}catch ( InterruptedException ex ){Logger.getLogger( EchoServer.class.getName() ).log( Level.SEVERE, null, ex );}}}

# 创建ServerBootstarp,用于Server端启动。

# 创建EventLoopGroup ,绑定于ServerBootstarp。

# 绑定使用NioServerSocketChannel

# 绑定端口

# 设置起动的ChannelInitialzer,在其管道对象中加入我们自定义的服务端处理的EchoHandler

# ServerBootstartp进行调用原来绑定,并阻塞等其执行完成,返回其ChannelFuture对象

# ChannelFuture.channel().closeFuture().sync() ,阻塞等待Server关闭。

# 释放EventLoopGroup所用的资源。

EchoServerHandler.java

@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter
{@Overridepublic void channelRead( ChannelHandlerContext ctx, Object msg ) throws Exception{//  System.out.println( "Server received :" + msg );//  ctx.write( msg );ByteBuf in = (ByteBuf) msg;System.out.println( "Server received: " + ByteBufUtil.hexDump( in ) );ctx.write( in );}@Overridepublic void channelReadComplete( ChannelHandlerContext ctx ) throws Exception{ctx.writeAndFlush( Unpooled.EMPTY_BUFFER ).addListener( ChannelFutureListener.CLOSE );}@Overridepublic void exceptionCaught( ChannelHandlerContext ctx, Throwable cause ) throws Exception{cause.printStackTrace();ctx.close();}}

# channelRead ,当获取到客户端信息时执行。通过ctx写回给客户端。

# 继承来自ChannelInboundHandlerAdapter,在执行完chanelRead方法后,释放相关NIO资源。

客户端

EchoClient.java

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.net.InetSocketAddress;/**** @author XzF*/
public class EchoClient
{private final String host;private final int port;public EchoClient( String host, int port ){this.host = host;this.port = port;}public void start() throws InterruptedException{EventLoopGroup group = new NioEventLoopGroup();try{Bootstrap bootstrap = new Bootstrap();bootstrap.group( group )//.channel( NioSocketChannel.class )//.remoteAddress( new InetSocketAddress( host, port ) )//.handler( new ChannelInitializer<SocketChannel>(){@Overrideprotected void initChannel( SocketChannel ch ) throws Exception{ch.pipeline().addLast( new EchoClientHandler() );}} );ChannelFuture f = bootstrap.connect().sync();f.channel().closeFuture().sync();}finally{group.shutdownGracefully().sync();}}public static void main( String[] args ){String host = "127.0.0.1";int port = 9999;if ( args.length > 0 ){host = args[0];port = Integer.parseInt( args[1] );}System.out.println("Usage: " + EchoClient.class.getSimpleName()+ " <host> " + host + " <port> :" + port );try{new EchoClient( host, port ).start();}catch ( InterruptedException ex ){ex.printStackTrace();}}}

#跟服务端大同小异,编写自定义EchoClientHandler

EchoClientHandler.java

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;/**** @author XzF*/
@Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf>
{@Overridepublic void channelActive( ChannelHandlerContext ctx ) throws Exception{String msg = "Netty rocks!";System.out.println( "Clinent sended : " + msg );ctx.writeAndFlush( Unpooled.copiedBuffer( msg, CharsetUtil.UTF_8 ) );}@Overrideprotected void channelRead0( ChannelHandlerContext ctx, ByteBuf in ) throws Exception{//  System.out.println( "Client received : "//                      + ByteBufUtil.hexDump( in.readBytes( in.readableBytes() ) ) );System.out.println("Client received: " + ByteBufUtil.hexDump(in));}@Overridepublic void exceptionCaught( ChannelHandlerContext ctx, Throwable cause ) throws Exception{cause.printStackTrace();ctx.close();}}

# channelActive ,在连接建立时调用,发送信息~

# channelRead0 ,当读取到服务端数据时调用。

# 继承SimpleChannelInboundHandler , 调用channelRead0 方法时不会及时清空资源,些类维护了NIO资源的释放,因不能保证一次调用channelRead0 方法已经将读取到的bytes全部带过来,但能维护顺序。

maven打包,编译后执行。

服务端:

客户端:

转载于:https://my.oschina.net/XzhiF/blog/262388

Netty笔记(一)第一个程序相关推荐

  1. actionscript 3.0 怎么写android 程序,(ActionScript3.0笔记)第一个程序HelloWorld!

    (ActionScript3.0笔记)第一个程序HelloWorld! 创建我的第一个ActionScript3.0程序--HelloWord! 首先下载ActionScript3.0的集成开发环境, ...

  2. CC2640R2F学习笔记(五.第一个程序:GPIO点灯)

    文章目录 前言 一.生成配置文件 二.导入工程"empty" 三.代码改动 四.实现点灯 前言 点灯似乎是所有MCU开发编写的第一个程序,使用CUBEMX来配置STM32初始化程序 ...

  3. 读书笔记——Python第一个程序Hello world

    2019独角兽企业重金招聘Python工程师标准>>> 开始学习python,随手写那么点笔记 ------------------------------------------- ...

  4. c#学习笔记之第一个程序“Hello world”

    看到"Hello world"的时候想起了一个笑话:一个退休多年的程序员决定练习书法,他拿起毛笔挥毫泼墨写下一行大字--"Hello world".虽然是一个笑 ...

  5. 第一个程序---汇编学习笔记

    第四章 第一个程序 4.1 一个源程序从写出到执行的过程 一个汇编语言程序从写到最终执行的简要过程. 编写汇编源程序 对源程序进行编译连接 执行可执行文件中的程序 如图所示: 4.2 源程序 程序代码 ...

  6. ROS入门笔记(九):编写ROS的第一个程序hello world(重点)

    ROS入门笔记(九):编写ROS的第一个程序hello world(重点) 文章目录 1 Catkin工作空间 1.1 创建catkin工作空间 1.2 编译工作空间 1.3 设置环境变量 1.4 检 ...

  7. contiki笔记2-contiki的第一个程序

    1.编写helloworld源代码 Contiki中每一个应用程序都需要一个单独的文件夹,我们为helloworld!建立一个名为helloworld的文件夹,并在其中创建 helloworld.c和 ...

  8. 黑马程序员C++学习笔记<第一阶段_基础篇>

    配套视频网址: 黑马程序员:http://yun.itheima.com/course/520.html?bili B站:https://www.bilibili.com/video/BV1et411 ...

  9. NRF51822开发笔记-2.Keil-MDK编译的第一个程序

    NRF51822开发笔记-2.Keil-MDK编译的第一个程序 1.进入安装路径,找到第一个实验Blinky_example,双击打开 2.编译 3.编译成功,无错误 4.生成了Hex文件 编译成功了

  10. [云炬ThinkPython阅读笔记]1.3 第一个程序

    1.3 第一个程序 根据惯例,学习使用一门语言写的第一个程序叫做 "Hello, World!" ,因为它的功能就 是显示单词 "Hello, World!" ...

最新文章

  1. 请收藏!新型冠状病毒感染的肺炎防控知识手册.pdf
  2. 1119: 零起点学算法26——判断奇偶数
  3. Regex 正则零宽断言
  4. _WIN32_WCE有什么用
  5. shiro学习(8):shiro连接数据库 三
  6. 新的 Windows Azure 网络安全性白皮书
  7. 转载:数据库应用开发工具Toad使用笔记
  8. percona-xtrabackup 文档
  9. 《复变函数论》试题库及答案
  10. html 讲课ppt,使用HTML制作网页讲课.ppt
  11. ai怎么做盒子效果图_仅需5步!手把手教你如何用AI绘制3D效果形象
  12. 如何评价『黑客与画家』
  13. 派森诺细菌完成图标准分析轻松发文
  14. 管理系统常用的jsp页面主模板
  15. 几何画板常见问题解决方案
  16. AI算法+EasyCVR打造智慧城市,构建万物互联智能世界
  17. web前端开发主要做什么?应该学些什么?
  18. minecraft_死后如何保存Minecraft物品(和其他聪明技巧)
  19. linux 字符界面 office,Linux系统下对比永中office和wps的界面及字体,附对比图
  20. 路由器R473g虚拟服务器设置,TL-R473G上网方式配置详解 路由器

热门文章

  1. 科学为什么重要?马化腾公开信引热议,透露企业未来发展方向
  2. 美媒:中关村取代硅谷获评全球最大科技中心
  3. 又双叒叕出事?微信 PC 版被曝扫描用户浏览器 cookies
  4. 从“人肉扩缩容”到云原生容量,90 后程序员的进化
  5. 再见,工资!程序员工资统计平均14404元,网友:又跌了!
  6. 程序员正在消失!90%的人都不知道,写不出好代码,是输在了这点上!
  7. HDU 6015 Skip the Class
  8. VMware中国的“七年之痒”,真的会有大动荡吗?
  9. 【预告】腾讯移动分析 MTA 即刻登陆 2017 GMTC 全球移动技术大会
  10. IDEA+Maven+Springboot:invalid bound statement (not found) 解决办法