个人主页网站制作教程电话号码宣传广告
文章目录
- 1. 版本
- 2. 入门例子,不返回消息
- 3. 扩展例子,返回消息
- 3.1 释放ByteBuf
官网文档
系列文章:
《Netty入门官方例子解析(一)丢弃服务器》
《Netty入门官方例子解析(二)Time Server》
《Netty入门官方例子解析(三)处理一个基于流的传输》
1. 版本
版本 netty4
maven依赖:
<dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.1.6.Final</version>
</dependency>
2. 入门例子,不返回消息
官方并没有使用Hello World来作为一个例子,而是采用RFC的DISCARD,这个协议定义了就是接收到请求后什么也不干。
第一步编写DiscardServerHandler类:
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
//ChannelInboundHandlerAdapter实现自ChannelInboundHandler
//ChannelInboundHandler提供了不同的事件处理方法你可以重写public class DiscardServerHandler extends ChannelInboundHandlerAdapter {/** * @说明:该方法用于接收从客户端接收的信息* * * @param ctx* * @param msg* * @throws Exception*/@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {// ByteBuf是一个引用计数对象实现ReferenceCounted,他就是在有对象引用的时候计数+1,无的时候计数-1,当为0对象释放内存ByteBuf in = (ByteBuf) msg;try {while (in.isReadable()) {System.out.print((char) in.readByte());System.out.flush();}} finally {// 丢弃ReferenceCountUtil.release(msg);}}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {cause.printStackTrace();ctx.close();}public void channelInactive(ChannelHandlerContext ctx) throws Exception {// channel失效处理,客户端下线或者强制退出等任何情况都触发这个方法System.out.println("关闭一个链接" + ctx.name());super.channelInactive(ctx);}@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {ctx.fireChannelActive();System.out.println("开启一个链接");}
第二步编写DiscardServer:
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;public class DiscardServer {private int port;public DiscardServer(int port){this.port = port;}public void run() throws Exception{//Group:群组,Loop:循环,Event:事件,这几个东西联在一起,相比大家也大概明白它的用途了。//Netty内部都是通过线程在处理各种数据,EventLoopGroup就是用来管理调度他们的,注册Channel,管理他们的生命周期。//NioEventLoopGroup是一个处理I/O操作的多线程事件循环//bossGroup作为boss,接收传入连接//因为bossGroup仅接收客户端连接,不做复杂的逻辑处理,为了尽可能减少资源的占用,取值越小越好EventLoopGroup bossGroup=new NioEventLoopGroup(1);//workerGroup作为worker,处理boss接收的连接的流量和将接收的连接注册进入这个workerEventLoopGroup workerGroup=new NioEventLoopGroup();try {//ServerBootstrap负责建立服务端//你可以直接使用Channel去建立服务端,但是大多数情况下你无需做这种乏味的事情ServerBootstrap b=new ServerBootstrap();b.group(bossGroup, workerGroup)//指定使用NioServerSocketChannel产生一个Channel用来接收连接.channel(NioServerSocketChannel.class)//ChannelInitializer用于配置一个新的Channel//用于向你的Channel当中添加ChannelInboundHandler的实现.childHandler(new ChannelInitializer<SocketChannel>() {public void initChannel(SocketChannel ch) throws Exception {//ChannelPipeline用于存放管理ChannelHandel//ChannelHandler用于处理请求响应的业务逻辑相关代码ch.pipeline().addLast(new DiscardServerHandler());};})//对Channel进行一些配置//注意以下是socket的标准参数//BACKLOG用于构造服务端套接字ServerSocket对象,标识当服务器请求处理线程全满时,用于临时存放已完成三次握手的请求的队列的最大长度。如果未设置或所设置的值小于1,Java将使用默认值50。//Option是为了NioServerSocketChannel设置的,用来接收传入连接的.option(ChannelOption.SO_BACKLOG, 128)//是否启用心跳保活机制。在双方TCP套接字建立连接后(即都进入ESTABLISHED状态)并且在两个小时左右上层没有任何数据传输的情况下,这套机制才会被激活。//childOption是用来给父级ServerChannel之下的Channels设置参数的.childOption(ChannelOption.SO_KEEPALIVE, true);// Bind and start to accept incoming connections.ChannelFuture f=b.bind(port).sync();// Wait until the server socket is closed.// In this example, this does not happen, but you can do that to gracefully// shut down your server.//sync()会同步等待连接操作结果,用户线程将在此wait(),直到连接操作完成之后,线程被notify(),用户代码继续执行//closeFuture()当Channel关闭时返回一个ChannelFuture,用于链路检测f.channel().closeFuture().sync();}finally{//资源优雅释放bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}public static void main(String[] args) {int port=8088;try {new DiscardServer(port).run();} catch (Exception e) {e.printStackTrace();}}
f.channel().closeFuture().sync();作用是产生一个wait()事件,保证main线程存活
,否则main线程直接结束了。
测试
打开Window的命令行,输入telnet命令:telnet localhost 8088,如果能够正确连接就代表成功,在新打开的命令窗口随意输入字符,如果在myeclipse当中能够正确输出在console当中,就代表程序正常。
在cmd中输入hello word回车,命令行没有字符显示,表明客户端没有收到任务响应消息
,我们看下myeclipse控制台的输出:
hello word
3. 扩展例子,返回消息
到目前为止,我们一直在使用数据而没有任何响应。 但是,通常应假定服务器对请求作出响应。 让我们学习如何通过实现ECHO协议将响应消息写到客户端,在ECHO协议中,任何接收到的数据都将被发回。
与前面例子实现的服务端丢弃消息的唯一区别在于,它会将接收到的数据发回,而不是将接收到的数据打印到控制台。 因此,再次修改channelRead()方法就足够了:
@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) {ctx.write(msg); // (1)ctx.flush(); // (2)}
ChannelHandlerContext对象提供了各种操作,使您能够触发各种I / O事件和操作。 在这里,我们调用write(Object)以逐字记录接收到的消息。 请注意,我们没有像前面的示例中那样释放收到的消息。 这是因为Netty在将其写到网络时会为您释放它
。
ctx.write(Object)不会将消息写出。 它在内部进行缓冲,然后通过ctx.flush()冲洗到电线上。 另外,您也可以简短地调用ctx.writeAndFlush(msg)
重新跑下代码,发现cmd命令行此时会显示字符。
3.1 释放ByteBuf
这里我有个疑问,如果没有write操作,是不是必须手动realease ByteBuf?
答案:从InBound里读取的ByteBuf要手动释放,还有自己创建的ByteBuf要自己负责释放。这两处要调用这个release方法。
write Bytebuf到OutBound时由netty负责释放,不需要手动调用release。
ReferenceCountUtil.release()其实是ByteBuf.release()方法,ReferenceCountUtil源码中release方法如下:
public static boolean release(Object msg) {if (msg instanceof ReferenceCounted) {return ((ReferenceCounted) msg).release();}return false;}
而ByteBuf 实现了ReferenceCounted接口
public abstract class ByteBuf implements ReferenceCounted