數據的流通是以byte的形式流通的,本文將通過字節轉換成字符串new String的方式打印出來
第一個handler,首先,往pipeline里加了第二個handler,也就是說,pipeline裏有兩個handler了,handler1負責接收最原始的ByteBuf對象(msg),似乎對neety來說第一個handler永遠都是ByteBuf,然後將ByteBuf轉換成字符串,打印該字符串,打印完畢之後,將該字符串傳遞到handler2中
public class MyServerHandler1 implements ChannelInboundHandler {
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
//動態往pipeline裏添加一個handler
ctx.pipeline().addLast(new MyServerHandler2());
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//因爲是第一個handler,所以msg是ByteBuf
ByteBuf bb = (ByteBuf) msg;
int len = bb.readableBytes();
byte[] bytes = new byte[len];
bb.readBytes(bytes);
String value = new String(bytes);
System.out.println("channelRead值:" + value);
//將一個String類型的字符串傳遞給第二個handler
ctx.fireChannelRead(value);
}
第二個handler
public class MyServerHandler2 implements ChannelInboundHandler {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//msg是從handler1中傳遞過來的String類型字符串
System.out.println(objName + ":channelRead,值:" + msg);
ctx.fireChannelRead(msg);
}
main方法
public static void main(String[] args) throws InterruptedException {
EventLoopGroup boosGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
//此處new MyServerHandler1
b.group(boosGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new MyServerHandler1());
ChannelFuture f = b.bind(9999).sync();
f.channel().closeFuture().sync();
啓動main方法,telnet命令,從鍵盤上按哪個字母,控制檯就會打印哪個字母