| 1) 客户端可以发送一个Student PoJo 对象到服务器 (通过 Protobuf 编码) |
| 2) 服务端能接收Student PoJo 对象,并显示信息(通过 Protobuf 解码) |
| |
| <dependency> |
| <groupId>com.google.protobuf</groupId> |
| <artifactId>protobuf-java</artifactId> |
| <version>3.6.1</version> |
| </dependency> |
| |
| |
| // https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java |
| implementation group: 'com.google.protobuf', name: 'protobuf-java', version: '3.21.1' |
- 在之前simple的基础上开发
- 新建Student.proto文件,并安装插件
| syntax = "proto3"; |
| option java_outer_classname = "StudentPOJO"; |
| |
| message Student { |
| int32 id = 1; |
| string name = 2; |
| } |

-
解压protoc-3.6.1-win32.zip
-
将Student.proto复制到如下目录

-
打卡cmd,输入如下命令

-
生成文件

-
将该文件复制到项目中

-
客户端配置如下
| @Override |
| protected void initChannel(SocketChannel ch) throws Exception { |
| ChannelPipeline pipeline = ch.pipeline(); |
| |
| pipeline.addLast("encoder", new ProtobufEncoder()); |
| pipeline.addLast(new NettyClientHandler()); |
| } |
| |
| @Override |
| public void channelActive(ChannelHandlerContext ctx) throws Exception { |
| |
| StudentPOJO.Student student = StudentPOJO.Student.newBuilder().setId(4).setName("智多星 吴用").build(); |
| |
| ctx.writeAndFlush(student); |
| } |
| @Override |
| protected void initChannel(SocketChannel ch) throws Exception { |
| ChannelPipeline pipeline = ch.pipeline(); |
| |
| |
| pipeline.addLast("decoder", new ProtobufDecoder(StudentPOJO.Student.getDefaultInstance())); |
| pipeline.addLast(new NettyServerHandler()); |
| } |
| public class NettyServerHandler extends ChannelInboundHandlerAdapter { |
| |
| |
| |
| |
| |
| |
| @Override |
| public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { |
| |
| |
| StudentPOJO.Student student = (StudentPOJO.Student) msg; |
| System.out.println("客户端发送的数据 id=" + student.getId() + " 名字=" + student.getName()); |
| } |
| } |
| |
| .....服务器 is ready... |
| 监听端口 6668 成功 |
| 客户端发送的数据 id=4 名字=智多星 吴用 |
| |
| |
| 客户端 ok.. |
| 服务器回复的消息:hello, 客户端~(>^ω^<)喵1 |
| 服务器的地址: /127.0.0.1:6668 |
| public class NettyServerHandler extends SimpleChannelInboundHandler<StudentPOJO.Student> { |
| |
| |
| |
| |
| |
| |
| @Override |
| public void channelRead0(ChannelHandlerContext ctx, StudentPOJO.Student msg) throws Exception { |
| |
| |
| System.out.println("客户端发送的数据 id=" + msg.getId() + " 名字=" + msg.getName()); |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
2021-08-09 错误处理
2021-08-09 spring boot文件上传