org.aotorrent.client.PeerRequestDecoder.java Source code

Java tutorial

Introduction

Here is the source code for org.aotorrent.client.PeerRequestDecoder.java

Source

/*
 * Copyright 2014 Napolov Dmitry
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.aotorrent.client;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.aotorrent.common.protocol.peer.*;

import java.util.List;

/**
 * @author dmitry 18.07.14 0:44
 */
class PeerRequestDecoder extends MessageToMessageDecoder<ByteBuf> {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4) {
            return;
        }
        final int messageLength = in.readInt();

        if (messageLength == 0) {
            return;
        }

        final byte messageTypeId = in.readByte();

        switch (messageTypeId) {
        case 0:
            out.add(new ChokeRequest());
            break;
        case 1:
            out.add(new UnChokeRequest());
            break;
        case 2:
            out.add(new InterestedRequest());
            break;
        case 3:
            out.add(new NotInterestedRequest());
            break;
        case 4:
            out.add(new HaveRequest(in.readInt()));
            break;
        case 5:
            out.add(new BitFieldRequest(in, messageLength - 1));
            break;
        case 6:
            out.add(new RequestRequest(in.readInt(), in.readInt(), in.readInt()));
            break;
        case 7:
            out.add(new PieceRequest(in.readInt(), in.readInt(), in.copy()));
            break;
        case 8:
            break; //TODO CancelRequest. make it
        case 9:
            break; //TODO PortRequest. make it too
        }
        //ReferenceCountUtil.release(in);
    }
}