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

netty发送接收16进制代码_netty tcp以16进制字节码的形式与硬件通信 netty 以16进制字节码和硬件通信技术交流QQ群 10934764531 核心代码 需要把16进制的字节码数组写入 byteBuf里面再发送给硬件才可以/*** 发送数据*/private static void send2client(ChannelHandlerContext channel, final String receiveStr) {try {// netty需要用ByteB... 阅读详情

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 作为一个非常优秀的网络通信框架,已经为我们提供了非常丰富的编解码抽象基类,帮助我们更方便地基于这些抽象基类扩展实现自定义协议。MessageToByteEncoder 对象编码成字节流;MessageToMessageEncoder 一种消息类型编码成另外一种消息类型。将字节流解码为消息对象;MessageToMessageDecoder 将一种消息类型解码为另外一种消息类型。 阅读详情

相关推荐

基于Netty实现自定义消息通信协议(协议设计及解析应用实战)

请求序号:基于双工协议,提供异步能力,也就是收到的异步消息需要找到前面的通信请求进行响应处理 消息长度 消息正文 协议定义 ==== sessionId | reqType | Content-Length | Content | 其中Version,Content-Length,SessionId就是Header信息,Content就是交互的主体。 定义项目结构以及引入包 io.netty netty-all org.slf4j slf4j-log4j12 org.projec..

tt8889的博客 959

Netty详解ByteBuf

目录 1 工作原理 2 基本使用 2.1 读取操作 2.2 写入操作 2.4 clear() 3 ByteBuf 使用模式 4 ByteBuf 的分配 5 ByteBuf的释放 5.1、⼿动释放 5.2 自动释放 5.2.1 TailHandler 5.2.2 SimpleChannelInboundHandler 5.2.3 HeadHandler 5.3 小结 1 工作原理 Java NIO 提供了ByteBuffer 作为它 的字节容器,但是这个类使⽤起来过于复杂,⽽且也有些繁琐。

赵广陆 4789

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

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

weixin_42451850的博客 702

ByteBuf 转为byte[] 不要用array()不对的。 JAVA 用内部类解决接口 交叉调用问题 2个串口实现透传,会相互在对方的接收接口实现里调用发送。

内部类在Java中提供了一种有效的方式来组织和封装代码,允许类之间实现更紧密的关系。不同类型的内部类适用于不同的场景,可以根据具体需求选择适合的内部类类型。

chenhao0568的专栏 2338

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

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

weixin_36364707的博客 509

Linux环境下使用线程方式操作UART读写功能

本文介绍Linux环境下使用线程方式操作UART的方法,实现了串口打开,关闭,发送数据,接收数据功能,还编写测试代码,验证该功能。

mftang的博客 2087

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

上文介绍了如何应用Netty开发自定义通讯协议,本文在此基础上进一步深化,研究如何同时支持不同的通讯协议。 此处所谓的通讯协议,指的是把Netty通讯管道中的二进制流转换为对象、把对象转换成二进制流的过程。转换过程追根究底还是ChannelInboundHandler、ChannelOutboundHandler的实现类在进行处理。ChannelInboundHandler负责把二进制流转换

bbaiggey_bigdata的博客 3514

C语言 100道经典编程题适用于专升本,专接本【详细分析版】_c语言专升本题目

/法2//left指向起始 right指向数组末尾= 0){left++;//如果*left是奇数就循环接着向后指,直到指向偶数就退出//(left

2401_84978503的博客 700
上一篇: Netty4.0学习笔记系列之四:混合使用coder和handler
下一篇: Netty4.0学习笔记系列之六:多种通讯协议支持
丨马平生丨
博客等级 码龄13年 163粉丝 59原创
评论 8
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值