Netty学习——Netty和Protobuf的整合


Protobuf作为序列化的工具,将序列化后的数据,通过Netty来进行在网络上的传输

1.将proto文件里的java包的位置修改一下,然后再执行一下protoc

异常捕获:启动服务器端正常,在启动客户端的时候,发送消息,报错

警告: An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.
io.netty.handler.codec.DecoderException: com.google.protobuf.InvalidProtocolBufferException: Protocol message contained an invalid tag (zero).
at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:)
at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:)
at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:)
at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:)
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:)
at io.netty.util.concurrent.SingleThreadEventExecutor$.run(SingleThreadEventExecutor.java:)
at io.netty.util.internal.ThreadExecutorMap$.run(ThreadExecutorMap.java:)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:)
at java.lang.Thread.run(Thread.java:)
Caused by: com.google.protobuf.InvalidProtocolBufferException: Protocol message contained an invalid tag (zero).
at com.google.protobuf.InvalidProtocolBufferException.invalidTag(InvalidProtocolBufferException.java:)
at com.google.protobuf.CodedInputStream$ArrayDecoder.readTag(CodedInputStream.java:)
at com.dawa.netty.sixthexample.MyDataInfo$Person.<init>(MyDataInfo.java:)
at com.dawa.netty.sixthexample.MyDataInfo$Person.<init>(MyDataInfo.java:)
at com.dawa.netty.sixthexample.MyDataInfo$Person$.parsePartialFrom(MyDataInfo.java:)
at com.dawa.netty.sixthexample.MyDataInfo$Person$.parsePartialFrom(MyDataInfo.java:)
at com.google.protobuf.AbstractParser.parsePartialFrom(AbstractParser.java:)
at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:)
at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:)
at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:)
at io.netty.handler.codec.protobuf.ProtobufDecoder.decode(ProtobufDecoder.java:)
at io.netty.handler.codec.protobuf.ProtobufDecoder.decode(ProtobufDecoder.java:)
at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:)
... more 十二月 , :: 上午 io.netty.channel.DefaultChannelPipeline onUnhandledInboundException
警告: An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.
io.netty.handler.codec.DecoderException: com.google.protobuf.InvalidProtocolBufferException: While parsing a protocol message, the input ended unexpectedly in the middle of a field. This could mean either that the input has been truncated or that an embedded message misreported its own length.
at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:)
at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:)
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:)
at io.netty.util.concurrent.SingleThreadEventExecutor$.run(SingleThreadEventExecutor.java:)
at io.netty.util.internal.ThreadExecutorMap$.run(ThreadExecutorMap.java:)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:)
at java.lang.Thread.run(Thread.java:)
Caused by: com.google.protobuf.InvalidProtocolBufferException: While parsing a protocol message, the input ended unexpectedly in the middle of a field. This could mean either that the input has been truncated or that an embedded message misreported its own length.
at com.google.protobuf.InvalidProtocolBufferException.truncatedMessage(InvalidProtocolBufferException.java:)
at com.google.protobuf.CodedInputStream$ArrayDecoder.readRawByte(CodedInputStream.java:)
at com.google.protobuf.CodedInputStream$ArrayDecoder.readRawVarint64SlowPath(CodedInputStream.java:)
at com.google.protobuf.CodedInputStream$ArrayDecoder.readRawVarint32(CodedInputStream.java:)
at com.google.protobuf.CodedInputStream$ArrayDecoder.readTag(CodedInputStream.java:)
at com.dawa.netty.sixthexample.MyDataInfo$Person.<init>(MyDataInfo.java:)
at com.dawa.netty.sixthexample.MyDataInfo$Person.<init>(MyDataInfo.java:)
at com.dawa.netty.sixthexample.MyDataInfo$Person$.parsePartialFrom(MyDataInfo.java:)
at com.dawa.netty.sixthexample.MyDataInfo$Person$.parsePartialFrom(MyDataInfo.java:)
at com.google.protobuf.AbstractParser.parsePartialFrom(AbstractParser.java:)
at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:)
at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:)
at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:)
at io.netty.handler.codec.protobuf.ProtobufDecoder.decode(ProtobufDecoder.java:)
at io.netty.handler.codec.protobuf.ProtobufDecoder.decode(ProtobufDecoder.java:)
at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:)
... more

开始找问题:
1.io.netty.handler.codec.DecoderException: 在解码过程中出错,可能是服务器端出的错
2.Caused by: com.google.protobuf.InvalidProtocolBufferException: Protocol message contained an invalid tag (zero).
3.While parsing a protocol message, the input ended unexpectedly in the middle of a field. This could mean either that the input has been truncated or that an embedded message misreported its own length.

检查了一下代码:猜测了一下:成了,效果图如下

可怕,原因竟然出现在编码器添加的顺序不同导致的: 正确的顺序是这样的:

@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//这里和之前的不一样了,但也就是处理器的不一样
//编解码处理器,protobuf提供的专门的编解码器.4个处理器
pipeline.addLast(new ProtobufVarint32FrameDecoder());
//Decoder是重点,解码器,将字节码转换成想要的数据类型
//参数 messageLite,外层的要转换的类的实例
pipeline.addLast(new ProtobufDecoder(MyDataInfo.Person.getDefaultInstance()));
pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
pipeline.addLast(new ProtobufEncoder());
pipeline.addLast(new TestServerHandler());
}

接下来存放一下完整的客户端和服务器端的代码
proto文件

yntax ="proto2";

package com.dawa.protobuf;

option optimize_for = SPEED;
option java_package ="com.dawa.netty.sixthexample";
option java_outer_classname = "MyDataInfo"; message Person{
required string name = ;
optional int32 age = ;
optional string address = ;
} message Person2{
required string name = ;
optional int32 age = ;
optional string address = ;
}

服务器端代码:

package com.dawa.netty.sixthexample;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler; /**
* @Title: TestServer
* @Author: 大娃
* @Date: 2019/12/3 10:01
* @Description:
*/
public class TestServer {
public static void main(String[] args) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup(); try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new TestServerInitializer()); ChannelFuture channelFuture = serverBootstrap.bind().sync();
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
package com.dawa.netty.sixthexample;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; /**
* @Title: TestServerHandler
* @Author: 大娃
* @Date: 2019/12/3 10:09
* @Description: handler本身是个泛型,这里的泛型就是取 要处理的类型
*/
public class TestServerHandler extends SimpleChannelInboundHandler<MyDataInfo.Person> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, MyDataInfo.Person msg) throws Exception {
//对接受到的消息进行处理:
System.out.println(msg.getName());
System.out.println(msg.getAge());
System.out.println(msg.getAddress());
}
}
package com.dawa.netty.sixthexample;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; /**
* @Title: TestServerInitializer
* @Author: 大娃
* @Date: 2019/12/3 10:05
* @Description:
*/
public class TestServerInitializer extends ChannelInitializer<SocketChannel> { @Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//这里和之前的不一样了,但也就是处理器的不一样
//编解码处理器,protobuf提供的专门的编解码器.4个处理器
pipeline.addLast(new ProtobufVarint32FrameDecoder());
//Decoder是重点,解码器,将字节码转换成想要的数据类型
//参数 messageLite,外层的要转换的类的实例
pipeline.addLast(new ProtobufDecoder(MyDataInfo.Person.getDefaultInstance()));
pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
pipeline.addLast(new ProtobufEncoder());
pipeline.addLast(new TestServerHandler());
}
}

客户端代码

package com.dawa.netty.sixthexample;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel; /**
* @Title: TestClient
* @Author: 大娃
* @Date: 2019/12/3 10:15
* @Description: 客户端内容
*/
public class TestClient {
public static void main(String[] args) throws Exception {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
.handler(new TestClientInitializer());
//注意此处,使用的是connect,不是使用的bind
ChannelFuture channelFuture = bootstrap.connect("localhost", ).sync();
channelFuture.channel().closeFuture().sync();
} finally {
eventLoopGroup.shutdownGracefully();
}
}
}
package com.dawa.netty.sixthexample;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; /**
* @Title: TestClientInitializer
* @Author: 大娃
* @Date: 2019/12/3 10:43
* @Description:
*/
public class TestClientInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//这里和之前的不一样了,但也就是处理器的不一样
//编解码处理器,protobuf提供的专门的编解码器.4个处理器
pipeline.addLast(new ProtobufVarint32FrameDecoder());
//Decoder是重点,解码器,将字节码转换成想要的数据类型
//参数 messageLite,外层的要转换的类的实例
pipeline.addLast(new ProtobufDecoder(MyDataInfo.Person.getDefaultInstance()));
pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
pipeline.addLast(new ProtobufEncoder());
//自己的处理器
pipeline.addLast(new TestClientHandler());
}
}
package com.dawa.netty.sixthexample;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler; /**
* @Title: TestClientHandler
* @Author: 大娃
* @Date: 2019/12/3 10:44
* @Description:
*/
public class TestClientHandler extends SimpleChannelInboundHandler<MyDataInfo.Person> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, MyDataInfo.Person msg) throws Exception { } @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//处于活动状态
MyDataInfo.Person person = MyDataInfo.Person.newBuilder().setName("大娃").setAge().setAddress("北京").build();
ctx.channel().writeAndFlush(person);
}
}

这程序是有瑕疵的,解码器那里不通用,耦合性太强,有两个很明显的问题,但是要怎么解决呢?

会专门写个帖子进行分析,Netty学习——Netty和Protobuf的整合(二)

Netty学习——Netty和Protobuf的整合(一)的更多相关文章

  1. Netty学习——Netty和Protobuf的整合(二)

    Netty学习——Netty和Protobuf的整合(二) 这程序是有瑕疵的,解码器那里不通用,耦合性太强,有两个很明显的问题,但是要怎么解决呢?如:再加一个内部类型 Person2,之前的代码就不能 ...

  2. netty学习--netty源码中的部分util方法

    io.netty.buffer.AbstractByteBuf#calculateNewCapacity  申请内存空间 private int calculateNewCapacity(int mi ...

  3. Netty学习篇③--整合springboot

    经过前面的netty学习,大概了解了netty各个组件的概念和作用,开始自己瞎鼓捣netty和我们常用的项目的整合(很简单的整合) 项目准备 工具:IDEA2017 jar包导入:maven 项目框架 ...

  4. Netty学习第一节Netty的总体概况

    一.Netty简介 什么是Netty? 1.高性能事件驱动,异步非阻塞的IO加载开源框架. 它是由JBoss提供,用于建立TCP等底层链接.基于Netty可以建立高性能的HTTP服务器,快速开发高性能 ...

  5. [置顶] Netty学习总结(1)——Netty入门介绍

    1.Netty是什么? Netty是一个基于JAVA NIO类库的异步通信框架,它的架构特点是:异步非阻塞.基于事件驱动.高性能.高可靠性和高可定制性. 2.使用Netty能够做什么? 开发异步.非阻 ...

  6. Netty学习——Thrift的入门使用

    Netty学习——Thrift的入门使用 希望你能够,了解并使用它.因为它是一个效率很高的框架 官网地址:http://thrift.apache.org/ 1.Thrift数据类型 一门技术如果需要 ...

  7. Netty学习——protoc的新手使用流程

    Netty学习——protoc的新手使用流程 关于学习的内容笔记,记下来的东西等于又过了一次脑子,记录的更深刻一些. 1. 使用IDEA创建.proto文件,软件会提示你安装相应的语法插件 安装成功之 ...

  8. netty学习资料

    netty学习资料推荐官方文档和<netty权威指南>和<netty in action>这两本书.下面收集下网上分享的资料 netty官方参考文档 Netty 4.x Use ...

  9. Netty学习之客户端创建

    一.客户端开发时序图 图片来源:Netty权威指南(第2版) 二.Netty客户端开发步骤 使用Netty进行客户端开发主要有以下几个步骤: 1.用户线程创建Bootstrap Bootstrap b ...

随机推荐

  1. mysql中的锁机制之悲观锁和乐观锁

    1.悲观锁? 悲观锁顾名思义就是很悲观,悲观锁认为数据随时就有可能会被外界进行修改,所以悲观锁一上来就会把数据给加上锁.悲观锁一般都是依靠关系型数据库提供的锁机制,然而事实上关系型数据库中的行锁,表锁 ...

  2. Eclipse SVN插件的帐号、密码修改

    Eclipse的SVN插件Subclipse做得很好,在svn操作方面提供了很强大丰富的功能.但到目前为止,该插件对svn用户的概念极为淡薄,不但不能方便地切换用户,而且一旦用户的帐号.密码保存之后, ...

  3. linux内核崩溃之kdump机制

    kdump相关概念 standard(production) kernel   生产内核    ,是指我们正在使用的kernel. Crash(capture)kernel             捕 ...

  4. 深入理解计算机系统 第三章 程序的机器级表示 part2

    这周由于时间和精力有限,只读一小节:3.4.4  压入和弹出栈数据 栈是一种特殊的数据结构,遵循“后进先出”的原则,可以用数组实现,总是从数组的一端插入和删除元素,这一端被称为栈顶. 栈有两个常用指令 ...

  5. 深入理解计算机系统 第三章 程序的机器级表示 part3

    这周看了刘老师提供的相关视频,以及书中对应的章节“3.7 过程” 这一节分为运行时栈.转移控制.数据传送.栈上的局部存储.寄存器中的局部存储空间和递归过程这 6 个小节 其中前 3 小节看懂了一部分内 ...

  6. 源码分析RocketMQ消息轨迹

    目录 1.发送消息轨迹流程 1.1 DefaultMQProducer构造函数 1.2 SendMessageTraceHookImpl钩子函数 1.3 TraceDispatcher实现原理 2. ...

  7. 彻底搞懂CSS伪类选择器:is、not

    本文介绍一下Css伪类:is和:not,并解释一下is.not.matches.any之前的关系 :not The :not() CSS pseudo-class represents element ...

  8. Redis入门,对Redis的理解和基本环境搭建及操作

    Redis入门使用 参考:https://blog.csdn.net/hellozpc/article/details/81267030 一).缓存的用途举例 1.前端页面广告的数据无需每次查询后台系 ...

  9. 更改input标签的placeholder的样式

    主要是要区别不同浏览器的不同css类 在input框中有时想将输入的字和placeholder设为不同的颜色或其它效果,这时就可以用以下代码来对placeholder进行样式设置了. input::- ...

  10. ftp用户和密码

    centos7 FTP修改密码: 1.查看ftp的用户:cat /etc/vsftpd/ftpusers 2.passwd ftp的用户 (输入两次) 3.重启ftp:service vsftpd r ...