netty——私有协议栈开垦案例

netty——私有协议栈开垦案例

摘要:

在求学江小鱼峰先生的Netty权威指南开中学,感觉第拾2章《私有协议栈开垦》中的案例代码相比较有代表性,讲的也没有错,可是代码中个人以为某些轻巧的不当,个人通过简要的改变,编写翻译好后展现给大家,有如何难题,希望留言,共同沟通;

相关包:

  • meven配置:

       <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>5.0.0.Alpha2</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.marshalling</groupId>
           
<artifactId>jboss-marshalling-serial</artifactId>
            <version>2.0.0.Beta2</version>
        </dependency>

  • 品种分布

图片 1

  • 代码

Nettymessage定义类


public final class  NettyMessage {
    private Header header;
    private Object body;
   
   
    public final Header getHeader() {
        return header;
    }
    public final void setHeader(Header header) {
        this.header = header;
    }
    public final Object getBody() {
        return body;
    }
    public final void setBody(Object body) {
        this.body = body;
    }
   
    public String toString(){
        return “NettyMessage [Header=”+header+”]”;
    }

}


音讯头定义类


public final class Header {
    private int crcCode = 0xabef0101;
    private int length;//音讯长度
    private long sessionID;//回话ID
    private byte type;//音讯类型
    private byte priority;//音信优先级
    private Map<String , Object> attachment = new
HashMap<String , Object>();//附件
   
   
    public final int getCrcCode() {
        return crcCode;
    }
    public final void setCrcCode(int crcCode) {
        this.crcCode = crcCode;
    }
    public final int getLength() {
        return length;
    }
    public final void setLength(int length) {
        this.length = length;
    }
    public final long getSessionID() {
        return sessionID;
    }
    public final void setSessionID(long sessionID) {
        this.sessionID = sessionID;
    }
    public final byte getType() {
        return type;
    }
    public final void setType(byte type) {
        this.type = type;
    }
    public final byte getPriority() {
        return priority;
    }
    public final void setPriority(byte priority) {
        this.priority = priority;
    }
    public final Map<String, Object> getAttachment() {
        return attachment;
    }
    public final void setAttachment(Map<String, Object>
attachment) {
        this.attachment = attachment;
    }
   
    public String toString(){
        return
“Headder[crcCode=]”+crcCode+”,length=”+length+”,sessionID=”
       
+sessionID+”,type=”+type+”,priority=”+priority+”attachment=”+attachment;
    }

}


概念新闻类型


public class MessageType {
    /**
     * 请求
     */
    public final static byte LOGIN_REQ = 0x01;
    /**
     * 回复
     */
    public final static byte LOGIN_RESP = 0x02;
    /**
     * 心跳请求
     */
    public final static byte HEARTBEAT_REQ = 0x03;
    /**
     * 心跳回复
     */
    public final static byte HEARTBEAT_RESP = 0x04;
}


定义 MarshallingCodeCFactory


import io.netty.handler.codec.marshalling.DefaultMarshallerProvider;
import io.netty.handler.codec.marshalling.DefaultUnmarshallerProvider;
import io.netty.handler.codec.marshalling.MarshallerProvider;
import io.netty.handler.codec.marshalling.UnmarshallerProvider;

import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;
/**
*
* @ClassName MarshallingCodeCFactory
* @Description TODOJBoss 马歇尔ing 是四个Java 对象系列化包,对 JDK
暗许的种类化框架实行了优化,<br>
* 但又保证跟 Java.io.塞里alizable
接口的相称,同时扩大了部分可调的参数和附属类小部件的特征,<br>
* 这么些参数和附加的特色, 那几个参数和特点可经过工厂类实行配置. 
马歇尔ing 构造工具
* @author lichunyang
* @Date 2017年4月13日 下午7:34:31
* @version 1.0.0
*/
public class MarshallingCodeCFactory {
   
    public static NettyMarshallingDecoder buildMarshallingDecoder(){
         /*
         * 通过 马歇尔ing 工具类的 getProvided马歇尔erFactory
         * 静态方法赢得马歇尔erFactory 实例, , 参数 serial
表示创造的是 Java 种类化学工业厂对象.它是由
         * jboss-marshalling-serial 包提供
         */
        final MarshallerFactory marshallerFactory =
Marshalling.getProvidedMarshallerFactory(“serial”);
        /**
         * 创建
         */
        final MarshallingConfiguration configuration = new
MarshallingConfiguration();
        configuration.setVersion(5);
        UnmarshallerProvider provider = new
DefaultUnmarshallerProvider(marshallerFactory, configuration);
        Netty马歇尔ingDecoder decoder = new
NettyMarshallingDecoder(provider, 拾2四);// 102四 单个对象最大尺寸
        return decoder;
    }
   
    public static NettyMarshallingEncoder buildMarshallingEncoder(){
        MarshallerFactory marshallerFactory =
Marshalling.getProvidedMarshallerFactory(“serial”);
        MarshallingConfiguration configuration = new
MarshallingConfiguration();
        configuration.setVersion(5);
        MarshallerProvider provider = new
DefaultMarshallerProvider(marshallerFactory, configuration);
        NettyMarshallingEncoder encoder = new
NettyMarshallingEncoder(provider);
        return encoder;
    }
}


定义 NettyMarshallingDecoder和NettyMarshallingEncoder


package netty.codefactory;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.marshalling.MarshallingDecoder;
import io.netty.handler.codec.marshalling.UnmarshallerProvider;
/**
*
* @ClassName NettyMarshallingDecoder
* @Description 增添马歇尔ingEncoder 和
马歇尔ingDecoder,将protected方法编制程序public能够调用<br>音讯解码工具类
* @author lichunyang
* @Date 2017年4月13日 下午7:22:03
* @version 1.0.0
*/
public class NettyMarshallingDecoder extends MarshallingDecoder {

    public NettyMarshallingDecoder(UnmarshallerProvider provider) {
        super(provider);
    }

    public NettyMarshallingDecoder(UnmarshallerProvider provider, int
maxObjectSize) {
        super(provider, maxObjectSize);
    }

    public Object decode(ChannelHandlerContext ctx, ByteBuf in) throws
Exception {
        return super.decode(ctx, in);
    }

}


package netty.codefactory;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.marshalling.MarshallerProvider;
import io.netty.handler.codec.marshalling.MarshallingEncoder;
/**
*
* @ClassName NettyMarshallingEncoder
* @Description 扩充马歇尔ingEncoder 和
马歇尔ingDecoder,将protected方法编制程序public能够调用<br>音信编码工具类
* @author lichunyang
* @Date 2017年4月13日 下午7:20:07
* @version 1.0.0
*/
public class NettyMarshallingEncoder extends MarshallingEncoder{

    public NettyMarshallingEncoder(MarshallerProvider provider) {
        super(provider);
    }

    public void encode(ChannelHandlerContext ctx, Object msg, ByteBuf
out) throws Exception{
        super.encode(ctx, msg, out);
    }
   
}


定义 NettyMessageDecoder和NettyMessageEncoder


package netty.codefactory;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import netty.message.Header;
import netty.message.NettyMessage;

import java.util.HashMap;
import java.util.Map;
/**
*
* @ClassName NettyMessageDecoder
* @Description 解码器
* @author lichunyang
* @Date 2017年4月13日 下午7:51:02
* @version 1.0.0
*/
public class NettyMessageDecoder extends LengthFieldBasedFrameDecoder{

    private NettyMarshallingDecoder marshallingDecoder;
   
    public NettyMessageDecoder(int maxFrameLength, int
lengthFieldOffset,
            int lengthFieldLength,int lengthAdjustment, int
initialBytesToStrip) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength,
lengthAdjustment, initialBytesToStrip);
        marshallingDecoder =
MarshallingCodeCFactory.buildMarshallingDecoder();
    }
   

    public Object decode(ChannelHandlerContext ctx, ByteBuf in) throws
Exception{
        ByteBuf frame = (ByteBuf)super.decode(ctx, in);
        if(frame == null){
            return null;
        }
       
        NettyMessage message = new NettyMessage();
        Header header = new Header();
        header.setCrcCode(frame.readInt());
        header.setLength(frame.readInt());
        header.setSessionID(frame.readLong());
        header.setType(frame.readByte());
        header.setPriority(frame.readByte());
       
        int size = frame.readInt();
        if(size > 0){
            Map<String, Object> attach = new HashMap<String,
Object>(size);
            int keySize = 0;
            byte[] keyArray = null;
            String key = null;
            for(int i=0; i<size; i++){
                keySize = frame.readInt();
                keyArray = new byte[keySize];
                in.readBytes(keyArray);
                key = new String(keyArray, “UTF-8”);
                attach.put(key, marshallingDecoder.decode(ctx,
frame));
            }
            key = null;
            keyArray = null;
            header.setAttachment(attach);
        }
        if(frame.readableBytes() > 0){
            message.setBody(marshallingDecoder.decode(ctx, frame));
        }
        message.setHeader(header);
        return message;
    }
}

相关文章