【Netty】读书笔记 - 跟闪电侠学
1. 内容概要
1.1 总结
1.1.1 逻辑处理器
ChannelHandler(详见 第11章 Pipeline与ChannelHandler)
1.1.2 编程小技巧
public class PacketCodeC {
...
public static final PacketCodeC INSTANCE = new PacketCodeC();
...
}
其他类直接调用 PacketCodeC.INSTANCE 即可使用PacketCodeC类的属性和方法
如:
PacketCodeC.INSTANCE.encode(ctx.alloc(), loginRequestPacket);
1.1.3 创建ByteBuf 对象的新方式
ByteBuf byteBuf = byteBufAllocator.ioBuffer();
其中
- byteBufAllocator 是 ctx.alloc() 返回的ByteBuf的分配器
- ctx 为 ChannelHandlerContext 通道处理上下文对象
1.1.4 写数据
ctx.channel().writeAndFlush(buffer);// 写数据
其中
- ctx.channel() 返回 Channel
1.1.5 instanceof 用法
作用:判断左边对象是否是右边类的实例/父类
public class ServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
System.out.println(new Date() + ": 客户端开始登录……");
ByteBuf requestByteBuf = (ByteBuf) msg;
Packet packet = PacketCodeC.INSTANCE.decode(requestByteBuf);
if (packet instanceof LoginRequestPacket) {
// 登录流程
LoginRequestPacket loginRequestPacket = (LoginRequestPacket) packet;
LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
loginResponsePacket.setVersion(packet.getVersion());
if (valid(loginRequestPacket)) {
loginResponsePacket.setSuccess(true);
System.out.println(new Date() + ": 登录成功!");
} else {
loginResponsePacket.setReason("账号密码校验失败");
loginResponsePacket.setSuccess(false);
System.out.println(new Date() + ": 登录失败!");
}
// 登录响应
ByteBuf responseByteBuf = PacketCodeC.INSTANCE.encode(ctx.alloc(), loginResponsePacket);
ctx.channel().writeAndFlush(responseByteBuf);
}
}
private boolean valid(LoginRequestPacket loginRequestPacket) {
return true;
}
}
2. 课程内容(略,请参考原书)
1 登录流程
2 逻辑处理器
3 客户端发送登录请求 + 返回响应
public class ClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) {
System.out.println(new Date() + ": 客户端开始登录");
// 创建登录对象
LoginRequestPacket loginRequestPacket = new LoginRequestPacket();
loginRequestPacket.setUserId(UUID.randomUUID().toString());
loginRequestPacket.setUsername("flash");
loginRequestPacket.setPassword("pwd");
// 编码
ByteBuf buffer = PacketCodeC.INSTANCE.encode(ctx.alloc(), loginRequestPacket);
// 写数据
ctx.channel().writeAndFlush(buffer);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf byteBuf = (ByteBuf) msg;
Packet packet = PacketCodeC.INSTANCE.decode(byteBuf);
if (packet instanceof LoginResponsePacket) {
LoginResponsePacket loginResponsePacket = (LoginResponsePacket) packet;
if (loginResponsePacket.isSuccess()) {
System.out.println(new Date() + ": 客户端登录成功");
} else {
System.out.println(new Date() + ": 客户端登录失败,原因:" + loginResponsePacket.getReason());
}
}
}
}