以前看了闪电侠的netty入门实战,对netty有了初步的了解。闪大的《netty 仿写IM即时通信》是针对tcp链接的,最近作实验要搭建集群,须要使用udp广播,因此把以前的tcp通信改成udp通信。java
tcp编解码器git
@Override
protected void encode(ChannelHandlerContext ctx, Packet packet, List<Object> list) throws Exception {
ByteBuf byteBuf = ctx.alloc().ioBuffer();
PacketCodec.INSTANCE.encode(byteBuf, packet);
list.add(byteBuf);
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> list) throws Exception {
list.add((PacketCodec.INSTANCE.decode(byteBuf)));
}
复制代码
udp编解码器github
@Override
protected void encode(ChannelHandlerContext ctx, Packet packet, List<Object> list) throws Exception {
ByteBuf byteBuf = ctx.alloc().ioBuffer();
PacketCodec.INSTANCE.encode(byteBuf, packet);
list.add(new DatagramPacket(byteBuf, address));
}
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket datagramPacket, List<Object> list) throws Exception {
Packet packet = PacketCodec.INSTANCE.decode(datagramPacket.content());
packet.setSender(datagramPacket.sender());
list.add(packet);
}
复制代码
udp 编解码器只需将DatagramPacket中的ByteBuf取出,而后使用以前自定义的tcp编解码器便可。tcp
其中 PacketCodec.INSTANCE.encode(byteBuf, packet)和PacketCodec.INSTANCE.decode(byteBuf)方法以下:ide
public void encode(ByteBuf byteBuf, Packet packet) {
//1.序列 java 对象
byte[] bytes = Serializer.DEFAULT.serialize(packet);
//2.实际编码过程
byteBuf.writeByte(packet.getCommand());
byteBuf.writeInt(bytes.length);
byteBuf.writeBytes(bytes);
}
public Packet decode(ByteBuf byteBuf) {
// 1.数据包指令
byte command = byteBuf.readByte();
// 2.数据包长度
int length = byteBuf.readInt();
byte[] bytes = new byte[length];
byteBuf.readBytes(bytes);
Class<? extends Packet> requestType = getRequestType(command);
Serializer serializer = Serializer.DEFAULT;
if (requestType != null && serializer != null) {
return serializer.deserialize(requestType, bytes);
}
return null;
}
复制代码
本文的代码在GitHub(https://github.com/zhangji-hhu/Netty-UDP)
。编码
本人目前仍是学生,但愿各位大佬批评指正!spa