netty tcp 改 udp

以前看了閃電俠的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

相關文章
相關標籤/搜索