Netty4.0学习笔记系列之六:多种通讯协议支持

2. Netty使用JSerialComm进行串口读取(二) 现在开始处理这些问题 第一个问题:串口读取超时异常一路传播到最后也没有处理。 ​ 第二个问题:即使处理了该异常,程序仍然退出,这不能满足一些实际使用要求需求。该问题与设置很长的读取超时时间没关系,无论多长到时间后总会退出。 阅读详情

上文介绍了如何应用Netty开发自定义通讯协议,本文在此基础上进一步深化,研究如何同时支持不同的通讯协议。

此处所谓的通讯协议,指的是把Netty通讯管道中的二进制流转换为对象、把对象转换成二进制流的过程。转换过程追根究底还是ChannelInboundHandler、ChannelOutboundHandler的实现类在进行处理。ChannelInboundHandler负责把二进制流转换为对象,ChannelOutboundHandler负责把对象转换为二进制流。

接下来要构建一个Server,同时支持Person通讯协议和String通讯协议。

  • Person通讯协议:二进制流与Person对象间的互相转换。
  • String通讯协议:二进制流与有固定格式要求的String的相互转换。String格式表示的也是一个Person对象,格式规定为:name:xx;age:xx;sex:xx;
这时候,来自客户端的请求,会依次传递给两个通讯解析接口进行解析,每个通讯接口判断是否是匹配的协议,如果是则进行解析,如果不是则传递给其它通讯接口进行解析。

实体类:Person
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
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;

// 测试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;
	}
}
4、BusinessHandler 展现客户端请求的内容
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();
	}
}


客户端1发送Person格式的协议:Client ClientInitHandler PersonEncoder
1、Client 
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);
	}
}
2、ClientInitHandler 向服务端发送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);
	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();
	}
}
3、PersonEncoder 把Person对象转换成二进制进行传送
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));
	}
}

客户端2发送String格式的协议:Client2 StringEncoder 同样使用了客户端1中定义的ClientInitHandler 进行数据发送操作。
1、Client2 
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);
	}
}
2、StringEncoder 把Person对象转换成固定格式的String的二进制流进行传送
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());
	}
}

其它:工具类ByteBufToBytes(读取ByteBuf数据的工具类)、ByteObjConverter(Object与byte互转的工具类)在以前的文章中已经存在,在此省略。

注意事项:
1、该段代码能运行出结果,但是运行的时候会报 io.netty.util.IllegalReferenceCountException: refCnt: 0, decrement: 1 异常,已经解决。日志中的提示信息为:
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
说明缺少exceptionCaught方法,在server端最后一个Handler中增加这个方法即可。
2、PersonDecoder和StringDecoder中有一个if判断,是为了判断消息究竟是什么协议。如果是String协议的话,格式是【name:xx;age:xx;sex:xx;】,第一个字母是英文字母n,所以判断协议类型时候是读取二进制流的第一个字符进行判断,当然这种判断方式非常幼稚,以后有机会可以进行改善。

netty实现多协议,多数据结构的最终解决方案 多对象,多数据类型,对协议,只要编解码器选择的正确,摆放的合理,照样能解决 阅读详情

相关推荐

Netty实战系列一之多协议并存

Netty实战系列一之多协议并存前言解决问题的思路主服务类ProtocolSelectorHandler协议选择器MyTextWebSocketFrameHandler服务端处理websocketMyHttpServerHandler服务端处理http自定义协议SimpleProtocol协议CustomEncoder自定义协议编码器CustomDecoder自定义协议解码器CutsomServe...

王伟王胖胖的博客 7603

An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means

问题描述:警告: 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. java.io.IOException: 远程主机强迫关闭了

cuiyaoqiang的博客 7万+

WebSocket介绍以及netty对于WebSocket的支持

1. 问题可以看看这几个场景应当怎么实现: 网页聊天应用 扫码登录成功跳转、支付成功跳转 网页游戏需要的实时数据交互 这些场景都是浏览器与服务端之间的交互,我们最容易想到的就是通过http协议来实现浏览器与服务端之间的交互。但是http协议是基于请求响应的,也就是每次的交互都是客户端发送请求,服务端返回响应。如果是服务端需要向客户端推送数据,http协议就不能够办到了。http要想实现上面的场景,必

zw19910924的专栏 1476

记录一次netty websocket 错误

异常意思是为在handler进行异常处理。初步异常处理代码如下解决方法:去掉: super.exceptionCaught(ctx,cause);异常处理重写就不需要走默认方法了。

want_to_future的博客 3784

Netty4.0学习笔记:掌握多种通讯协议支持与高效网络通信

Netty 是一个高性能的异步事件驱动的网络应用程序框架,用于快速开发可维护的高性能协议服务器和客户端。它是基于Java NIO(New IO,非阻塞IO)实现的,具有易于使用、性能高、稳定性强的特点。Netty 的设计理念是利用尽可能少的资源,实现高并发、低延迟的网络通信,以此来满足企业级应用对于网络通信性能的要求。Netty 的核心组件包括 Reactor 模型、Channel、ChannelHandler、EventLoop 以及 ByteBuf 等。

weixin_42451850的博客 702

Netty4.0自定义通讯协议学习与实战

Netty 通过一个名为Channel的核心抽象,为网络通信提供了丰富的API和可扩展的架构。Channel代表了一个与远程节点的连接,可以进行读写操作。Netty 框架的组件都围绕着Channel来设计,包括了线程模型、缓冲处理、编解码器等关键概念。自定义编码器需要实现接口,并重写encode方法。下面是一个简单的自定义编码器的实现示例:@Override// 序列化消息对象// 分配足够的空间// 写入序列化后的数据} else {

weixin_36364707的博客 509

SpringBoot 集成 Netty 作为服务端常用 TCP/UDP 通讯协议示例

文章目录1 摘要2 通讯协议3 核心代码3.1 Netty 服务器3.2 Netty 服务端工具类3.3 Netty 服务处理器3.4 协议请求头封装类4 测试4.1 测试工具4.2 测试数据4.2 测试数据 1 摘要 在 IoT 物联网设备通讯领域,服务端和设备端的通讯通常基于 TCP/UDP 协议,在这些协议的基础上定义自己的私有通讯协议。本文将介绍 SpringBoot 集成 Netty 在服务端常用的TCP、UDP通讯协议示例。 SpringBoot 集成 Netty 作为服务端: SpringBo

Mrqiang9001 3703

AI+Xmind自动生成测试用例(思维导图格式)

最后:我是Walker,一个热爱分享编程知识的程序员,希望能够帮助到你!

Think_and_work的博客 2348

【手撸IM】通讯协议设计与实现

之前说过要手撸一个 IM 需要考虑的东西太多了,以至于前期做的很多工作与 IM 本身其实并没有太多直接的关系,例如:分布式策略、接入服务等。上一篇抛砖引玉的介绍了消息IM的设计与实现,现在谈下如何设计与实现一个私有的通讯协议。

bossfriday - 个人博客 2108

CocosCreator 面试题(十五)Cocos Creator如何内置protobuf JS版本?

接着,它创建了一个 Player 对象,并使用 protobuf.js 提供的 API 对其进行序列化和反序列化操作。其中,name 和 level 是普通的字段,items 是一个 repeated 字段,表示它可以包含多个值。在 Cocos Creator 中使用 protobuf.js,我们需要先加载 .proto 文件,然后使用 protobuf.js 提供的 API 进行序列化和反序列化操作。JSON和XML是文本格式,更易于阅读和调试,而且在对人类友好的接口和数据交换上更为常见和广泛支持。

w风雨无阻w的专栏 2634

【最全】ISTQB- FL模拟题(含答案)

汇总收集的所有ISTQB基础级考题和答案

maoxuexue的博客 1万+

Netty4.0学习笔记系列之五:自定义通讯协议

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34148340的博客 81

Innovus ECO修复时序违例:ecoAddRepeater插Buffer原理与实战

芯片物理设计越到后期,时序收敛越依赖局部修正而非全局重跑。ECO(Engineering Change Order)作为数字后端高频操作,能在不破坏既有布局布线结果的前提下,精准修复DRV违例、hold时序问题或实现功能补丁。其中,插入Buffer或Inverter是拆解长线RC负载、改善max_transition/max_capacitance最直接的手段。Innovus提供的ecoAddRepeater命令封装了单元选择、坐标摆放和网表重连等底层细节,配合ecoRoute可快速完成绕线。合理选型Buf

weixin_31858171的博客 308
上一篇: Netty4.0学习笔记系列之五:自定义通讯协议
下一篇: RFC6455-The WebSocket protocol 之二:Conformance Requirements
丨马平生丨
博客等级 码龄13年 163粉丝 59原创
评论 5
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值