Netty學習6-ChanelHandler【1】概述

1 概述


Handler在netty中無疑佔據着非常重要的地位。Handler與Servlet中的filter很像,通過Handler可以完成通訊報文的解碼編碼、攔截指定的報文、統一對日誌錯誤進行處理、統一對請求進行計數、控制Handler執行與否等等。

Netty4.X中的所有handler都實現自ChannelHandler接口。按照輸出輸出來分爲ChannelInboundHandler、ChannelOutboundHandler兩大類。


ChannelInboundHandler:對接收的信息進行處理。一般用來執行解碼、讀取客戶端數據、進行業務處理等。如StringDecoder
ChannelOutboundHandler:對發送的信息進行處理,一般用來進行編碼、發送報文到客戶端。如StringEncoder

Netty中可以註冊多個handler。ChannelInboundHandler按照註冊的先後順序執行。ChannelOutboundHandler按照註冊的先後順序逆序執行。按照註冊的先後順序對Handler進行排序,request進入Netty後的執行順序爲:





2 實例


該例模擬Client與Server間的通訊。Server端註冊2個ChannelInboundHandler、2個ChannelOutboundHandler。當Client連接到Server後,會向Server發送一條消息。Server端通過ChannelInboundHandler 對Client的消息進行讀取,通過ChannelOutboundHandler向client發送消息。

Server端共5個類:HelloServer、InboundHandler1、InboundHandler2、OutboundHandler1、OutboundHandler2

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 HelloServer {
	public void start(int port) throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup(); 
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap(); 
			b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) 
					.childHandler(new ChannelInitializer<SocketChannel>() { 
								@Override
								public void initChannel(SocketChannel ch) throws Exception {
									// 註冊兩個OutboundHandler,執行順序爲註冊順序的逆序,所以應該是OutboundHandler2 OutboundHandler1
									ch.pipeline().addLast(new OutboundHandler1());
									ch.pipeline().addLast(new OutboundHandler2());
									// 註冊兩個InboundHandler,執行順序爲註冊順序,所以應該是InboundHandler1 InboundHandler2
									ch.pipeline().addLast(new InboundHandler1());
									ch.pipeline().addLast(new InboundHandler2());
								}
							}).option(ChannelOption.SO_BACKLOG, 128) 
					.childOption(ChannelOption.SO_KEEPALIVE, true); 

			ChannelFuture f = b.bind(port).sync(); 
			f.channel().closeFuture().sync();
		} finally {
			workerGroup.shutdownGracefully();
			bossGroup.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws Exception {
		HelloServer server = new HelloServer();
		server.start(8000);
	}
}


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class InboundHandler1 extends ChannelInboundHandlerAdapter {
	private static Logger	logger	= LoggerFactory.getLogger(InboundHandler1.class);

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		logger.info("InboundHandler1.channelRead: ctx :" + ctx);
		// 通知執行下一個InboundHandler
		ctx.fireChannelRead(msg);
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		logger.info("InboundHandler1.channelReadComplete");
		ctx.flush();
	}
}


import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class InboundHandler2 extends ChannelInboundHandlerAdapter {
	private static Logger	logger	= LoggerFactory.getLogger(InboundHandler2.class);

	@Override
	// 讀取Client發送的信息,並打印出來
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		logger.info("InboundHandler2.channelRead: ctx :" + ctx);
		ByteBuf result = (ByteBuf) msg;
		byte[] result1 = new byte[result.readableBytes()];
		result.readBytes(result1);
		String resultStr = new String(result1);
		System.out.println("Client said:" + resultStr);
		result.release();
		ctx.write(msg);
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		logger.info("InboundHandler2.channelReadComplete");
		ctx.flush();
	}
}


import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OutboundHandler1 extends ChannelOutboundHandlerAdapter {
	private static Logger	logger	= LoggerFactory.getLogger(OutboundHandler1.class);
	@Override
	// 向client發送消息
	public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
		logger.info("OutboundHandler1.write");
		String response = "I am ok!";
		ByteBuf encoded = ctx.alloc().buffer(4 * response.length());
		encoded.writeBytes(response.getBytes());
		ctx.write(encoded);
		ctx.flush();
	}
}

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class OutboundHandler2 extends ChannelOutboundHandlerAdapter {
	private static Logger	logger	= LoggerFactory.getLogger(OutboundHandler2.class);
	
	@Override
	public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
		logger.info("OutboundHandler2.write");
		// 執行下一個OutboundHandler
		super.write(ctx, msg, promise);
	}
}
Client端有兩個類:HelloClient、HelloClientHandler

import io.netty.bootstrap.Bootstrap;
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.NioSocketChannel;
public class HelloClient {
	public void connect(String host, int port) throws Exception {
		EventLoopGroup workerGroup = new NioEventLoopGroup();

		try {
			Bootstrap b = new Bootstrap();
			b.group(workerGroup);
			b.channel(NioSocketChannel.class);
			b.option(ChannelOption.SO_KEEPALIVE, true);
			b.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				public void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(new HelloClientIntHandler());
				}
			});
			// Start the client.
			ChannelFuture f = b.connect(host, port).sync();
			f.channel().closeFuture().sync();
		} finally {
			workerGroup.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws Exception {
		HelloClient client = new HelloClient();
		client.connect("127.0.0.1", 8000);
	}
}


import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloClientHandler extends ChannelInboundHandlerAdapter {
	private static Logger	logger	= LoggerFactory.getLogger(HelloClientIntHandler.class);
	@Override
	// 讀取服務端的信息
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		logger.info("HelloClientIntHandler.channelRead");
		ByteBuf result = (ByteBuf) msg;
		byte[] result1 = new byte[result.readableBytes()];
		result.readBytes(result1);
		result.release();
		ctx.close();
		System.out.println("Server said:" + new String(result1));
	}
	@Override
	// 當連接建立的時候向服務端發送消息 ,channelActive 事件當連接建立的時候會觸發
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		logger.info("HelloClientIntHandler.channelActive");
		String msg = "Are you ok?";
		ByteBuf encoded = ctx.alloc().buffer(4 * msg.length());
		encoded.writeBytes(msg.getBytes());
		ctx.write(encoded);
		ctx.flush();
	}
}
inboundHandler1
inboundHandler2
Client said:are you ok?
outboundHandler2
outboundHandler1



3 總結


[1] ChannelInboundHandler間的傳遞通過調用 ctx.fireChannelRead(msg) 實現,調用ctx.write(msg)將傳遞到ChannelOutboundHandler

[2] ctx.write()方法執行後,需要調用flush()方法才能令它立即執行。

[3] ChannelOutboundHandler在註冊時,需要放在最後一個ChannelInboundHandler之前,否則將無法傳遞到ChannelOutboundHandler。


原貼地址:http://blog.csdn.net/u012635819/article/details/50828339


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章