Netty筆記之八:自定義通信協(xié)議

Netty中雙方建立通信之后,對象數(shù)據(jù)會按照ByteBuf字節(jié)碼的方式進行傳輸娃善。

自定義一種通信協(xié)議焚虱,協(xié)議將傳輸數(shù)據(jù)定義了消息頭和消息正文订框。

管道中傳遞LuckMessage對象,LuckMessage中定義了消息頭LuckHeader和消息正文content晨另。消息頭header包括version潭千,contentLength,sessionId借尿。

消息定義:

// 消息的頭部
public class LuckHeader {

    // 協(xié)議版本
    private int version;
    // 消息內(nèi)容長度
    private int contentLength;
    // 服務(wù)名稱
    private String sessionId;

    public LuckHeader(int version, int contentLength, String sessionId) {
        this.version = version;
        this.contentLength = contentLength;
        this.sessionId = sessionId;
    }

    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }

    public int getContentLength() {
        return contentLength;
    }

    public void setContentLength(int contentLength) {
        this.contentLength = contentLength;
    }

    public String getSessionId() {
        return sessionId;
    }

    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }
}

// 消息的主體
public class LuckMessage {

    private LuckHeader luckHeader;
    private String content;

    public LuckMessage(LuckHeader luckHeader, String content) {
        this.luckHeader = luckHeader;
        this.content = content;
    }

    public LuckHeader getLuckHeader() {
        return luckHeader;
    }

    public void setLuckHeader(LuckHeader luckHeader) {
        this.luckHeader = luckHeader;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return String.format("[version=%d,contentLength=%d,sessionId=%s,content=%s]",
                luckHeader.getVersion(),
                luckHeader.getContentLength(),
                luckHeader.getSessionId(),
                content);
    }
}

服務(wù)端代碼:

public class LuckServer {

    public static void main(String args[]) throws InterruptedException {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {

            ServerBootstrap serverBootstrap = new ServerBootstrap();
            // 指定socket的一些屬性
            serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)  // 指定是一個NIO連接通道
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new LuckServerInitializer());

            // 綁定對應(yīng)的端口號,并啟動開始監(jiān)聽端口上的連接
            Channel ch = serverBootstrap.bind(8899).sync().channel();

            System.out.printf("luck協(xié)議啟動地址:127.0.0.1:%d/\n", 8899);

            // 等待關(guān)閉,同步端口
            ch.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

服務(wù)端初始化連接:

package com.zhihao.miao.test.day08;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;

public class LuckServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel channel) throws Exception {

        ChannelPipeline pipeline = channel.pipeline();

        pipeline.addLast(new LuckEncoder());
        pipeline.addLast(new LuckDecoder());
        // 添加邏輯控制層
        pipeline.addLast(new LuckServerHandler());

    }
}

編碼Handler:

package com.zhihao.miao.test.day08;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class LuckEncoder extends MessageToByteEncoder<LuckMessage> {

    @Override
    protected void encode(ChannelHandlerContext ctx, LuckMessage message, ByteBuf out) throws Exception {

        // 將Message轉(zhuǎn)換成二進制數(shù)據(jù)
        LuckHeader header = message.getLuckHeader();

        // 這里寫入的順序就是協(xié)議的順序.

        // 寫入Header信息
        out.writeInt(header.getVersion());
        out.writeInt(message.getContent().length());
        out.writeBytes(header.getSessionId().getBytes());

        // 寫入消息主體信息
        out.writeBytes(message.getContent().getBytes());
    }
}

解碼器Handler:

package com.zhihao.miao.test.day08;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class LuckDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

        // 獲取協(xié)議的版本
        int version = in.readInt();
        // 獲取消息長度
        int contentLength = in.readInt();
        // 獲取SessionId
        byte[] sessionByte = new byte[36];
        in.readBytes(sessionByte);
        String sessionId = new String(sessionByte);

        // 組裝協(xié)議頭
        LuckHeader header = new LuckHeader(version, contentLength, sessionId);

        // 讀取消息內(nèi)容刨晴,這邊demo中不對
        byte[] contentbys = new byte[in.readableBytes()];
        in.readBytes(contentbys);

        String content = new String(contentbys);

        LuckMessage message = new LuckMessage(header, content);

        out.add(message);
    }
}

自定義服務(wù)端handler處理器:

package com.zhihao.miao.test.day08;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class LuckServerHandler extends SimpleChannelInboundHandler<LuckMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LuckMessage msg) throws Exception {
        // 簡單地打印出server接收到的消息
        System.out.println(msg.toString());
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("service exception:"+cause.getMessage());
    }
}

客戶端:

package com.zhihao.miao.test.day08;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.UUID;

public class LuckClient {

    public static void main(String args[]) throws InterruptedException {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .handler(new LuckServerInitializer());

            // Start the connection attempt.
            Channel ch = b.connect("127.0.0.1", 8899).sync().channel();

            int version = 1;
            String sessionId = UUID.randomUUID().toString();
            String content = "I'm the luck protocol!";

            LuckHeader header = new LuckHeader(version, content.length(), sessionId);
            LuckMessage message = new LuckMessage(header, content);
            ch.writeAndFlush(message);

            ch.close();

        } finally {
            group.shutdownGracefully();
        }
    }
}

客戶端初始化連接:

package com.zhihao.miao.test.day08;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;

public class LuckClientInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel channel) throws Exception {

        ChannelPipeline pipeline = channel.pipeline();

        // 添加編解碼器, 由于ByteToMessageDecoder的子類無法使用@Sharable注解,
        // 這里必須給每個Handler都添加一個獨立的Decoder.
        pipeline.addLast(new LuckEncoder());
        pipeline.addLast(new LuckDecoder());

        pipeline.addLast(new LuckClientHandler());

    }
}

客戶端自定義handler:

package com.zhihao.miao.test.day08;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class LuckClientHandler extends SimpleChannelInboundHandler<LuckMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, LuckMessage message) throws Exception {
        System.out.println(message);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("client exception:"+cause.getMessage());
    }
}

啟動服務(wù)器和客戶端,服務(wù)器端控制臺打勇贩:

七月 04, 2017 5:22:27 下午 io.netty.handler.logging.LoggingHandler channelRead
信息: [id: 0x9df966cc, L:/0:0:0:0:0:0:0:0:8899] READ: [id: 0x99c6480a, L:/127.0.0.1:8899 - R:/127.0.0.1:55722]
七月 04, 2017 5:22:27 下午 io.netty.handler.logging.LoggingHandler channelReadComplete
信息: [id: 0x9df966cc, L:/0:0:0:0:0:0:0:0:8899] READ COMPLETE
[version=1,contentLength=22,sessionId=c9345f67-99b6-46d2-97ff-eef853c9d569,content=I'm the luck protocol!]

完整demo

參考資料

利用Netty構(gòu)建自定義協(xié)議的通信

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末狈癞,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子茂契,更是在濱河造成了極大的恐慌蝶桶,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,826評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件掉冶,死亡現(xiàn)場離奇詭異真竖,居然都是意外死亡,警方通過查閱死者的電腦和手機郭蕉,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評論 3 395
  • 文/潘曉璐 我一進店門疼邀,熙熙樓的掌柜王于貴愁眉苦臉地迎上來喂江,“玉大人召锈,你說我怎么就攤上這事』裱” “怎么了涨岁?”我有些...
    開封第一講書人閱讀 164,234評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長吉嚣。 經(jīng)常有香客問我梢薪,道長,這世上最難降的妖魔是什么尝哆? 我笑而不...
    開封第一講書人閱讀 58,562評論 1 293
  • 正文 為了忘掉前任秉撇,我火速辦了婚禮,結(jié)果婚禮上秋泄,老公的妹妹穿的比我還像新娘琐馆。我一直安慰自己,他們只是感情好恒序,可當我...
    茶點故事閱讀 67,611評論 6 392
  • 文/花漫 我一把揭開白布瘦麸。 她就那樣靜靜地躺著,像睡著了一般歧胁。 火紅的嫁衣襯著肌膚如雪滋饲。 梳的紋絲不亂的頭發(fā)上厉碟,一...
    開封第一講書人閱讀 51,482評論 1 302
  • 那天,我揣著相機與錄音屠缭,去河邊找鬼箍鼓。 笑死,一個胖子當著我的面吹牛呵曹,可吹牛的內(nèi)容都是我干的袄秩。 我是一名探鬼主播,決...
    沈念sama閱讀 40,271評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼逢并,長吁一口氣:“原來是場噩夢啊……” “哼之剧!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起砍聊,我...
    開封第一講書人閱讀 39,166評論 0 276
  • 序言:老撾萬榮一對情侶失蹤背稼,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后玻蝌,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體蟹肘,經(jīng)...
    沈念sama閱讀 45,608評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,814評論 3 336
  • 正文 我和宋清朗相戀三年俯树,在試婚紗的時候發(fā)現(xiàn)自己被綠了帘腹。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,926評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡许饿,死狀恐怖阳欲,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情陋率,我是刑警寧澤球化,帶...
    沈念sama閱讀 35,644評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站瓦糟,受9級特大地震影響筒愚,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜菩浙,卻給世界環(huán)境...
    茶點故事閱讀 41,249評論 3 329
  • 文/蒙蒙 一巢掺、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧劲蜻,春花似錦陆淀、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至坝初,卻和暖如春浸剩,著一層夾襖步出監(jiān)牢的瞬間钾军,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評論 1 269
  • 我被黑心中介騙來泰國打工绢要, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留吏恭,地道東北人。 一個月前我還...
    沈念sama閱讀 48,063評論 3 370
  • 正文 我出身青樓重罪,卻偏偏與公主長得像樱哼,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子剿配,可洞房花燭夜當晚...
    茶點故事閱讀 44,871評論 2 354

推薦閱讀更多精彩內(nèi)容