netty 自定义通讯协议
Netty中,通讯的双方建立连接后,会把数据按照ByteBuf的方式进行传输,例如http协议中,就是通过HttpRequestDecoder对ByteBuf数据流进行处理,转换成http的对象。基于这个思路,我自定义一种通讯协议:Server和客户端直接传输java对象。
实现的原理是通过Encoder把java对象转换成ByteBuf流进行传输,通过Decoder把ByteBuf转换成java对象进行处理,处理逻辑如下图所示:
传输的java bean为Person:
- package com.guowl.testobjcoder;
- import java.io.Serializable;
- // 必须实现Serializable接口
- public class Person implements Serializable{
- private static final long serialVersionUID = 1L;
- private String name;
- private String sex;
- private int age;
- public String toString() {
- return "name:" + name + " sex:" + sex + " age:" + age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getSex() {
- return sex;
- }
- public void setSex(String sex) {
- this.sex = sex;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
Server端类:Server PersonDecoder BusinessHandler
1、Server:启动netty服务
- package com.guowl.testobjcoder;
- import io.netty.bootstrap.ServerBootstrap;
- import io.netty.channel.ChannelFuture;
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.ChannelOption;
- import io.netty.channel.EventLoopGroup;
- import io.netty.channel.nio.NioEventLoopGroup;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.channel.socket.nio.NioServerSocketChannel;
- public class Server {
- public void start(int port) throws Exception {
- EventLoopGroup bossGroup = new NioEventLoopGroup();
- EventLoopGroup workerGroup = new NioEventLoopGroup();
- try {
- ServerBootstrap b = new ServerBootstrap();
- b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
- .childHandler(new ChannelInitializer<SocketChannel>() {
- @Override
- public void initChannel(SocketChannel ch) throws Exception {
- ch.pipeline().addLast(new PersonDecoder());
- ch.pipeline().addLast(new BusinessHandler());
- }
- }).option(ChannelOption.SO_BACKLOG, 128)
- .childOption(ChannelOption.SO_KEEPALIVE, true);
- ChannelFuture f = b.bind(port).sync();
- f.channel().closeFuture().sync();
- } finally {
- workerGroup.shutdownGracefully();
- bossGroup.shutdownGracefully();
- }
- }
- public static void main(String[] args) throws Exception {
- Server server = new Server();
- server.start(8000);
- }
- }
2、PersonDecoder:把ByteBuf流转换成Person对象,其中ByteBufToBytes是读取ButeBuf的工具类,上一篇文章中提到过,在此不在详述。ByteObjConverter是byte和obj的互相转换的工具。
- package com.guowl.testobjcoder;
- import io.netty.buffer.ByteBuf;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.handler.codec.ByteToMessageDecoder;
- import java.util.List;
- import com.guowl.utils.ByteBufToBytes;
- import com.guowl.utils.ByteObjConverter;
- public class PersonDecoder extends ByteToMessageDecoder {
- @Override
- protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
- ByteBufToBytes read = new ByteBufToBytes();
- Object obj = ByteObjConverter.ByteToObject(read.read(in));
- out.add(obj);
- }
- }
3、BusinessHandler 读取Person信息,并打印
- package com.guowl.testobjcoder;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelInboundHandlerAdapter;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class BusinessHandler extends ChannelInboundHandlerAdapter {
- private Logger logger = LoggerFactory.getLogger(BusinessHandler.class);
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- Person person = (Person) msg;
- logger.info("BusinessHandler read msg from client :" + person);
- }
- @Override
- public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
- ctx.flush();
- }
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- }
- }
Client端的类:Client ClientInitHandler PersonEncoder
1、Client 建立与Server的连接
- package com.guowl.testobjcoder;
- import io.netty.bootstrap.Bootstrap;
- import io.netty.channel.ChannelFuture;
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.ChannelOption;
- import io.netty.channel.EventLoopGroup;
- import io.netty.channel.nio.NioEventLoopGroup;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.channel.socket.nio.NioSocketChannel;
- public class Client {
- public void connect(String host, int port) throws Exception {
- EventLoopGroup workerGroup = new NioEventLoopGroup();
- try {
- Bootstrap b = new Bootstrap();
- b.group(workerGroup);
- b.channel(NioSocketChannel.class);
- b.option(ChannelOption.SO_KEEPALIVE, true);
- b.handler(new ChannelInitializer<SocketChannel>() {
- @Override
- public void initChannel(SocketChannel ch) throws Exception {
- ch.pipeline().addLast(new PersonEncoder());
- ch.pipeline().addLast(new ClientInitHandler());
- }
- });
- ChannelFuture f = b.connect(host, port).sync();
- f.channel().closeFuture().sync();
- } finally {
- workerGroup.shutdownGracefully();
- }
- }
- public static void main(String[] args) throws Exception {
- Client client = new Client();
- client.connect("127.0.0.1", 8000);
- }
- }
2、ClientInitHandler 向Server发送Person对象
- package com.guowl.testobjcoder;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelInboundHandlerAdapter;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class ClientInitHandler extends ChannelInboundHandlerAdapter {
- private static Logger logger = LoggerFactory.getLogger(ClientInitHandler.class);
- @Override
- public void channelActive(ChannelHandlerContext ctx) throws Exception {
- logger.info("HelloClientIntHandler.channelActive");
- Person person = new Person();
- person.setName("guowl");
- person.setSex("man");
- person.setAge(30);
- ctx.write(person);
- ctx.flush();
- }
- }
3、PersonEncoder 把Person对象转换成ByteBuf进行传送
- package com.guowl.testobjcoder;
- import com.guowl.utils.ByteObjConverter;
- import io.netty.buffer.ByteBuf;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.handler.codec.MessageToByteEncoder;
- public class PersonEncoder extends MessageToByteEncoder<Person> {
- @Override
- protected void encode(ChannelHandlerContext ctx, Person msg, ByteBuf out) throws Exception {
- byte[] datas = ByteObjConverter.ObjectToByte(msg);
- out.writeBytes(datas);
- ctx.flush();
- }
- }
工具类:ByteObjConverter
- package com.guowl.utils;
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- public class ByteObjConverter {
- public static Object ByteToObject(byte[] bytes) {
- Object obj = null;
- ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
- ObjectInputStream oi = null;
- try {
- oi = new ObjectInputStream(bi);
- obj = oi.readObject();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- bi.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- try {
- oi.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return obj;
- }
- public static byte[] ObjectToByte(Object obj) {
- byte[] bytes = null;
- ByteArrayOutputStream bo = new ByteArrayOutputStream();
- ObjectOutputStream oo = null;
- try {
- oo = new ObjectOutputStream(bo);
- oo.writeObject(obj);
- bytes = bo.toByteArray();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- bo.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- try {
- oo.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return (bytes);
- }
- }
通过上述代码,实现了Server端与Client端直接使用person对象进行通信的目的。基于此,可以构建更为复杂的场景:Server端同时支撑多种协议,不同的协议采用不同的Decoder进行解析,解析结果保持统一,这样业务处理类可以保持接口一致。下一节将编写这样一个案例。
本例中需要注意的事项是:
1、Person对象必须实现Serializable接口,否则不能进行序列化。
2、PersonDecoder读取ByteBuf数据的时候,并没有对多次流式数据进行处理,而是简单的一次性接收,如果数据量大的情况下,可能会出现数据不完整,这个问题会在后续的学习中解决。
netty 自定义通讯协议的更多相关文章
- Netty 对通讯协议结构设计的启发和总结
Netty 通讯协议结构设计的总结 key words: 通信,协议,结构设计,netty,解码器,LengthFieldBasedFrameDecoder 原创 包含与机器/设备的通讯协议结构的设计 ...
- netty 自定义协议
netty 自定义协议 netty 是什么呢? 相信很多人都被人问过这个问题.如果快速准确的回复这个问题呢?网络编程框架,netty可以让你快速和简单的开发出一个高性能的网络应用.netty是一个网络 ...
- netty 支持多种通讯协议
通讯协议,指的是把Netty通讯管道中的二进制流转换为对象.把对象转换成二进制流的过程.转换过程追根究底还是ChannelInboundHandler.ChannelOutboundHandler的实 ...
- 《精通并发与Netty》学习笔记(14 - 解决TCP粘包拆包(二)Netty自定义协议解决粘包拆包)
一.Netty粘包和拆包解决方案 Netty提供了多个解码器,可以进行分包的操作,分别是: * LineBasedFrameDecoder (换行) LineBasedFrameDecoder是回 ...
- 基于Netty的RPC架构学习笔记(九):自定义序列化协议
文章目录 为什么需要自定义序列化协议
- 基于dubbo框架下的RPC通讯协议性能测试
一.前言 Dubbo RPC服务框架支持丰富的传输协议.序列化方式等通讯相关的配置和扩展.dubbo执行一次RPC请求的过程大致如下:消费者(Consumer)向注册中心(Registry)执行RPC ...
- HslCommunication库的二次协议扩展,适配第三方通讯协议开发,基础框架支持长短连接模式
本文将使用一个gitHub开源的项目来扩展实现二次协议的开发,该项目已经搭建好了基础层架构,并实现了三菱,西门子,欧姆龙,MODBUS-TCP的通讯示例,也可以参照这些示例开发其他的通讯协议,并Pul ...
- websocket通讯协议(10版本)简介
前言: 工作中用到了websocket 协议10版本的,英文的协议请看这里: http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotoc ...
- 【转】西门子PLC以太网 通讯协议 解析
一直想把三菱和西门子这两个使用频率最高的PLC上位通讯,融合到WCS系统的框架里: 现在三菱主流使用Q系列,使用的是MC协议, 前一段时间也写过一个入门介绍: 三菱Q系列通讯方式设计说明 去年8月份, ...
随机推荐
- nginx开启gzip压缩前端css,js
利用nginx实现前后端分离, nginx配置文件,nginx.conf配置采用gzip压缩: 在server中添加: gzip on; #开启gzip gzip_min_length 1k; #低于 ...
- PHP 5.2、5.3、5.4、5.5、5.6 对比以及功能详解
php5.2.x php5.3.x php5.4.x php5.5.x php5.6.x 对比详解 截至目前(2014.2), PHP 的最新稳定版本是 PHP5.5, 但有差不多一半的用户仍在使用已 ...
- MVC的博客
一个基于Asp.net MVC的博客类网站开源了! 背景说明: 大学时毕业设计作品,一直闲置在硬盘了,倒想着不如开源出来,也许会对一些人有帮助呢,而且个人觉得这个网站做得还是不错了,毕竟是花了不少 ...
- Air Raid HDU 1151
题意 给定n个路口 加上一些单向路 求遍历完所有路口需要多少人 人是空降的 哪里都可以作为起点 求 最小边覆盖 (用最少的边覆盖所有的点) 也叫最小路径覆盖(更形象) 也叫二分图的最大独立集 ...
- 001.KVM介绍
KVM介绍可参考: http://liqingbiao.blog.51cto.com/3044896/1740516 http://koumm.blog.51cto.com/703525/128879 ...
- 使用eclipse svn塔建(配置)时的一点点心得
有没有人遇到下面这种情况??自己创建的SVN如下: 但网上别人搭建好的是这样子的: 就是为什么我的只有个主文件,而没有src.webroot.meta-inf.web-inf等子文件呢?? 这是我找了 ...
- 自己的reset.css
复制.粘贴 /* http://www.cnblogs.com/ele-cat Reset Stylesheet v1.0.1 2018-05-08 Author: Ele-cat - http:// ...
- 不同浏览器的userAgent
一.IE浏览器 //IE6 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)" //IE7 "Mozill ...
- 错误跳转js
<script type="text/javascript"> var t = 5; //倒计时的秒数 function showTime(){ document.ge ...
- 缩减apk大小
韩梦飞沙 韩亚飞 313134555@qq.com yue31313 han_meng_fei_sha 1,重复的资源,不用的资源,删去. 2,使用混淆,可以优化. 3,尽量的使用代码,或者其 ...