Netty4.0学习笔记系列之六:多种通讯协议支持
上文介绍了如何应用Netty开发自定义通讯协议,本文在此基础上进一步深化,研究如何同时支持不同的通讯协议。
此处所谓的通讯协议,指的是把Netty通讯管道中的二进制流转换为对象、把对象转换成二进制流的过程。转换过程追根究底还是ChannelInboundHandler、ChannelOutboundHandler的实现类在进行处理。ChannelInboundHandler负责把二进制流转换为对象,ChannelOutboundHandler负责把对象转换为二进制流。
接下来要构建一个Server,同时支持Person通讯协议和String通讯协议。
- Person通讯协议:二进制流与Person对象间的互相转换。
- String通讯协议:二进制流与有固定格式要求的String的相互转换。String格式表示的也是一个Person对象,格式规定为:name:xx;age:xx;sex:xx;
- package com.guowl.testobjcoder;
- import java.io.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 StringDecoder BusinessHandler
- 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;
- // 测试coder 和 handler 的混合使用
- 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 StringDecoder());
- 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 把二进制流转换成Person对象
- 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 {
- byte n = "n".getBytes()[0];
- byte p = in.readByte();
- in.resetReaderIndex();
- if (n != p) {
- // 把读取的起始位置重置
- ByteBufToBytes reader = new ByteBufToBytes();
- out.add(ByteObjConverter.byteToObject(reader.read(in)));
- } else {
- // 执行其它的decode
- ctx.fireChannelRead(in);
- }
- }
- }
3、StringDecoder 把满足条件的字符串转换成Person对象
- 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;
- public class StringDecoder extends ByteToMessageDecoder {
- @Override
- protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
- // 判断是否是String协议
- byte n = "n".getBytes()[0];
- byte p = in.readByte();
- // 把读取的起始位置重置
- in.resetReaderIndex();
- if (n == p) {
- ByteBufToBytes reader = new ByteBufToBytes();
- String msg = new String(reader.read(in));
- Person person = buildPerson(msg);
- out.add(person);
- //in.release();
- } else {
- ctx.fireChannelRead(in);
- }
- }
- private Person buildPerson(String msg) {
- Person person = new Person();
- String[] msgArray = msg.split(";|:");
- person.setName(msgArray[1]);
- person.setAge(Integer.parseInt(msgArray[3]));
- person.setSex(msgArray[5]);
- return 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();
- }
- <span style="white-space:pre"> </span>// 解决注意事项1中的问题。
- <pre name="code" class="java"><span style="white-space:pre"> </span>@Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
- ctx.close();
- }
}
- 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());
- Person person = new Person();
- person.setName("guowl");
- person.setSex("man");
- person.setAge(30);
- ch.pipeline().addLast(new ClientInitHandler(person));
- }
- });
- 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);
- }
- }
- 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);
- private Person person;
- public ClientInitHandler(Person person){
- this.person = person;
- }
- @Override
- public void channelActive(ChannelHandlerContext ctx) throws Exception {
- logger.info("ClientInitHandler.channelActive");
- ctx.write(person);
- ctx.flush();
- }
- }
- 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 {
- out.writeBytes(ByteObjConverter.objectToByte(msg));
- }
- }
- package com.guowl.testobjcoder.client2;
- 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;
- import com.guowl.testobjcoder.ClientInitHandler;
- import com.guowl.testobjcoder.Person;
- public class Client2 {
- 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 StringEncoder());
- Person person = new Person();
- person.setName("guoxy");
- person.setSex("girl");
- person.setAge(4);
- ch.pipeline().addLast(new ClientInitHandler(person));
- }
- });
- ChannelFuture f = b.connect(host, port).sync();
- f.channel().closeFuture().sync();
- } finally {
- workerGroup.shutdownGracefully();
- }
- }
- public static void main(String[] args) throws Exception {
- Client2 client = new Client2();
- client.connect("127.0.0.1", 8000);
- }
- }
- package com.guowl.testobjcoder.client2;
- import io.netty.buffer.ByteBuf;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.handler.codec.MessageToByteEncoder;
- import com.guowl.testobjcoder.Person;
- public class StringEncoder extends MessageToByteEncoder<Person> {
- @Override
- protected void encode(ChannelHandlerContext ctx, Person msg, ByteBuf out) throws Exception {
- // 转成字符串:name:xx;age:xx;sex:xx;
- StringBuffer sb = new StringBuffer();
- sb.append("name:").append(msg.getName()).append(";");
- sb.append("age:").append(msg.getAge()).append(";");
- sb.append("sex:").append(msg.getSex()).append(";");
- out.writeBytes(sb.toString().getBytes());
- }
- }
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
Netty4.0学习笔记系列之六:多种通讯协议支持相关推荐
- SQLServer学习笔记系列2
SQLServer学习笔记系列2 一.写在前面的话 继上一次SQLServer学习笔记系列1http://www.cnblogs.com/liupeng61624/p/4354983.html以后,继 ...
- CCC3.0学习笔记_数字密钥数据结构
CCC3.0学习笔记_数字密钥数据结构 系列文章目录 文章目录 系列文章目录 前言 4.1 Applet Instance Layout 4.2 Digital Key Structure 4.2.1 ...
- 《SVM笔记系列之六》支持向量机中的核技巧那些事儿
<SVM笔记系列之六>支持向量机中的核技巧那些事儿 前言 我们在前文[1-5]中介绍了线性支持向量机的原理和推导,涉及到了软和硬的线性支持向量机,还有相关的广义拉格朗日乘数法和KKT条件等 ...
- SQL Server 2008/2012中SQL应用系列及BI学习笔记系列--目录索引
SQL Server 2008中的一些特性总结及BI学习笔记系列,欢迎与邀月交流. 3w@live.cn ◆0.SQL应用系列 1.SQL Server 2008中SQL增强之一:Values新用途 ...
- BizTalk学习笔记系列之二:实例说明如何使用BizTalk
BizTalk学习笔记系列之二:实例说明如何使用BizTalk --.BizTalk学习笔记系列之二<?XML:NAMESPACE PREFIX = O /> Aaron.Gao,2006 ...
- 线程基础知识——Windows核心编程学习手札系列之六
线程基础知识 --Windows核心编程学习手札系列之六 线程与进程一样由两部分构成:一是线程的内核对象,操作系统用它来对线程实施管理,也是系统用来存放线程统计信息的地方:二是线程堆栈,用于维护线程在 ...
- CCC3.0学习笔记_认证和隐私保护
CCC3.0学习笔记_Authentication and Privacy Keys 系列文章目录 文章目录 系列文章目录 前言 1. 手机端和车厂服务器端的密钥存储 2. 密钥的产生和使用的说明 3 ...
- CodeMonkey过关学习笔记系列:46-55关 数组
CodeMonkey过关学习笔记系列:46-55关 •"数组"索引 (ARRAY INDEXING) 46~55 第 46 关挑战 当我们有一根以上的香蕉时,我们可以用 [] 这个 ...
- CodeMonkey过关学习笔记系列:71-85关 函数
CodeMonkey过关学习笔记系列:71-75关 •"函数"农场 (FUNCTION FARM) 71 ~ 85 第 71 关挑战 "函数"农场step di ...
- CCC3.0学习笔记_证书数据
CCC3.0学习笔记_证书数据 系列文章目录 文章目录 系列文章目录 前言 1. [A] - SE Root CA Certificate 2. [B] - SE Root Certificate 3 ...
最新文章
- adc 接收cube_官方的stm32cube软件教程实例ADC操作代码(官方自带的,可以无视
- 阿里资深AI工程师教你逐个击破机器学习核心算法
- [VC6] 图像文件格式数据查看器
- 使用fscanf读取文本文件
- 关于.NET前后台提示框的那点事
- 告别2013,迎接2014
- 【Laravel】只保留Auth::routes()的登录,关闭Auth::routes()的注册、重置密码、验证路由
- mysql 测试快生产慢_生产上MySQL慢查询优化实战,SQL优化实战
- pyecharts第四节、漏斗图
- Hibernate之悲观锁与乐观锁
- C语言项目:黑客帝国之数字雨
- LeetCode —— 145. 二叉树的后序遍历【递归与迭代】(Python)
- 对损失函数的总结(持续更新)
- freecplus框架-ftp客户端
- python字符串 切片_Python切片字符串
- CheckedListBoxControl 实现复选框的单选与多选功能
- java 解析mp4文件头_视频文件头解析--MP4-获取mp4 文件信息
- 土壤修复废水除镍技术,除镍树脂材料
- 最强下载神器IDM的安装和使用
- SpringCloud之Zuul微服务网关 什么是Zuul微服务网关?
热门文章
- 阶段3 2.Spring_03.Spring的 IOC 和 DI_12 注入集合数据
- 阶段3 1.Mybatis_12.Mybatis注解开发_1 mybatis注解开发的环境搭建
- asp.net5开发中DNX SDK版本的影响
- 几种不同程序语言的HMM版本
- Android Studio 安装说明
- SharePoint 2010-在ribbon上添加表单,将默认control加到自定义group中
- FreeBSD 8.0候选版本RC2发布
- SpringMvc源码入门
- Markdown 表格
- 小程序或者APP 自行使用TOKEN 实现登录会话保持