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
netty 支持多种通讯协议的更多相关文章
- MySQL 通讯协议
Client/Server 通讯协议用于客户端链接.代理.主备复制等,支持 SSL.压缩,在链接阶段进行认证,在执行命令时可以支持 Prepared Statements 以及 Stored Proc ...
- ActiveMQ学习笔记(7)----ActiveMQ支持的传输协议
1. 连接到ActiveMQ Connector: Active提供的,用来实现连接通讯的功能,包括:client-to-broker,broker-to-broker.ActiveMQ允许客户端使用 ...
- Netty 对通讯协议结构设计的启发和总结
Netty 通讯协议结构设计的总结 key words: 通信,协议,结构设计,netty,解码器,LengthFieldBasedFrameDecoder 原创 包含与机器/设备的通讯协议结构的设计 ...
- netty 自定义通讯协议
Netty中,通讯的双方建立连接后,会把数据按照ByteBuf的方式进行传输,例如http协议中,就是通过HttpRequestDecoder对ByteBuf数据流进行处理,转换成http的对象.基于 ...
- RPC基于http协议通过netty支持文件上传下载
本人在中间件研发组(主要开发RPC),近期遇到一个需求:RPC基于http协议通过netty支持文件上传下载 经过一系列的资料查找学习,终于实现了该功能 通过netty实现文件上传下载,主要在编解码时 ...
- HslCommunication库的二次协议扩展,适配第三方通讯协议开发,基础框架支持长短连接模式
本文将使用一个gitHub开源的项目来扩展实现二次协议的开发,该项目已经搭建好了基础层架构,并实现了三菱,西门子,欧姆龙,MODBUS-TCP的通讯示例,也可以参照这些示例开发其他的通讯协议,并Pul ...
- 基于dubbo框架下的RPC通讯协议性能测试
一.前言 Dubbo RPC服务框架支持丰富的传输协议.序列化方式等通讯相关的配置和扩展.dubbo执行一次RPC请求的过程大致如下:消费者(Consumer)向注册中心(Registry)执行RPC ...
- Mavlink - 无人机通讯协议
http://qgroundcontrol.org/mavlink/start mavlink协议介绍https://pixhawk.ethz.ch/mavlink/ 消息简介 MAVLink简介 M ...
- Modbus通讯协议
<ignore_js_op> O1CN01P1wxTI1dCdw5nAeMO_!!85243700.jpg (287.43 KB, 下载次数: 0) 下载附件 保存到相册 2019-6- ...
随机推荐
- java 其它可选方法
异常处理的一个原则时,只有当你在知道如何处理的情况下才捕获异常,异常处理的一个重要目标时将错误处理代码同错误发生的地点相分离. "被检查异常"强制你在还没准备好处理错误的时候被迫加 ...
- Sublime Text 使用介绍/全套快捷键及插件推荐
如果说Notepad++是一款不错Code神器,那么Sublime Text应当称得上是神器滴哥.Sublime Text最大的优点就是跨平台,Mac和Windows均可完美使用:其次是强大的插件支持 ...
- ADO.Net练习1
一. 1.Car表数据查出显示2.请输入要查的汽车名称: 请输入要查的汽车油耗: 请输入要查的汽车马力: static void Main(string[] args) { SqlCo ...
- 【LOJ】#2075. 「JSOI2016」位运算
题解 压的状态是一个二进制位,我们规定1到n的数字互不相同是从小到大,二进制位记录的是每一位和后一个数是否相等,第n位记录第n个数和原串是否相等,处理出50个转移矩阵然后相乘,再快速幂即可 代码 #i ...
- Codeforces Round #355 (Div. 2) D. Vanya and Treasure
题目大意: 给你一个n × m 的图,有p种宝箱, 每个点上有一个种类为a[ i ][ j ]的宝箱,a[ i ][ j ] 的宝箱里有 a[ i ][ j ] + 1的钥匙,第一种宝箱是没有锁的, ...
- rabbitMQ的安装(Windows下)
在公司接触到这一块,信息中间件的使用,在公司没有时间了解的更加深入,只是在简单的使用,这里将深入学习一番. 参考:http://blog.csdn.net/lu1005287365/article/d ...
- 007 jquery过滤选择器-----------(屬性过滤选择器)
1.介紹 2.程序 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> < ...
- css样式大全整理
字体属性:(font) 大小 {font-size: x-large;}(特大) xx-small;(极小) 一般中文用不到,只要用数值就可以,单位:PX.PD 样式 {font-style: obl ...
- C#开发Unity游戏教程之Unity中方法的参数
C#开发Unity游戏教程之Unity中方法的参数 Unity的方法的参数 出现在脚本中的方法,无论是在定义的时候,还是使用的时候,后面都跟着一对括号“( )”,有意义吗?看起来最多也就是起个快速识别 ...
- python django + js 使用ajax进行文件上传并获取上传进度案例
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...