1 Handler链调用-需求
使用自定义的编码器和解码器来说明Netty的Handler调用机制。客户端发送long类型数据到服务端;服务端发送long到客户端。
2 Handler链调用-实战
2.1 NettyServer.java
public class NettyServer {
public static void main(String[] args) {
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new MyServerInitializer());//自定义一个初始化类
ChannelFuture sync = serverBootstrap.bind(8000).sync();
sync.channel().closeFuture().sync();
}catch (Exception e){
e.printStackTrace();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
2.2 MyServerInitializer.java
public class MyServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//对入站的Hadler进行解码
pipeline.addLast(new MyByteToLongDecoder2());
//对出站的Handler进行解码
pipeline.addLast(new MyLongToByteEncoder());
//自定义Handler
pipeline.addLast(new MyServerHandler());
}
}
2.3 MyByteToLongDecoder2.java
public class MyByteToLongDecoder2 extends ReplayingDecoder<Void> {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
System.out.println("MyByteToLongDecoder2 被调用");
out.add(in.readLong());
}
}
2.4 MyLongToByteEncoder.java
public class MyLongToByteEncoder extends MessageToByteEncoder<Long> {
@Override
protected void encode(ChannelHandlerContext ctx, Long msg, ByteBuf out) throws Exception {
System.out.println("MyLongToByteEncoder 被调用");
System.out.println("msg = " + msg);
out.writeLong(msg);
}
}
2.5 MyServerHandler.java
public class MyServerHandler extends SimpleChannelInboundHandler<Long> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception {
System.out.println("从客户端:"+ctx.channel().remoteAddress() + "读取到long类型数据:"+msg);
//向客户端发送一个long类型数据
ctx.writeAndFlush(123456L);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
2.6 NettyClient.java
public class NettyClient {
public static void main(String[] args) {
NioEventLoopGroup g = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(g)
.channel(NioSocketChannel.class)
.handler(new MyClientInitializer());
ChannelFuture sync = bootstrap.connect("127.0.0.1",