Netty中,通讯的双方建立连接后,会把数据按照ByteBuf的方式进行传输,例如http协议中,就是通过HttpRequestDecoder对ByteBuf数据流进行处理,转换成http的对象。基于这个思路,我自定义一种通讯协议:Server和客户端直接传输java对象。

实现的原理是通过Encoder把java对象转换成ByteBuf流进行传输,通过Decoder把ByteBuf转换成java对象进行处理,处理逻辑如下图所示:

客户端:

package cn.itcast_03_netty.sendobject.client;import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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 java.net.InetSocketAddress;import cn.itcast_03_netty.sendobject.coder.PersonEncoder;/*** • 连接服务器 • 写数据到服务器 • 等待接受服务器返回相同的数据 • 关闭连接* * @author wilson**/
public class EchoClient {private final String host;private final int port;public EchoClient(String host, int port) {this.host = host;this.port = port;}public void start() throws Exception {EventLoopGroup nioEventLoopGroup = null;try {// 创建Bootstrap对象用来引导启动客户端Bootstrap bootstrap = new Bootstrap();// 创建EventLoopGroup对象并设置到Bootstrap中,EventLoopGroup可以理解为是一个线程池,这个线程池用来处理连接、接受数据、发送数据nioEventLoopGroup = new NioEventLoopGroup();// 创建InetSocketAddress并设置到Bootstrap中,InetSocketAddress是指定连接的服务器地址bootstrap.group(nioEventLoopGroup)//
                    .channel(NioSocketChannel.class)//
                    .remoteAddress(new InetSocketAddress(host, port))//
                    .handler(new ChannelInitializer<SocketChannel>() {//// 添加一个ChannelHandler,客户端成功连接服务器后就会被执行
                                @Overrideprotected void initChannel(SocketChannel ch)throws Exception {// 注册编码的handlerch.pipeline().addLast(new PersonEncoder());  //out//注册处理消息的handlerch.pipeline().addLast(new EchoClientHandler());   //in
                                }});// • 调用Bootstrap.connect()来连接服务器ChannelFuture f = bootstrap.connect().sync();// • 最后关闭EventLoopGroup来释放资源
            f.channel().closeFuture().sync();} finally {nioEventLoopGroup.shutdownGracefully().sync();}}public static void main(String[] args) throws Exception {new EchoClient("localhost", 20000).start();}
}

package cn.itcast_03_netty.sendobject.client;import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;import java.io.Serializable;import cn.itcast_03_netty.sendobject.bean.Person;public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {// 客户端连接服务器后被调用
    @Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {System.out.println("EchoClientHandler.....channelActive");Person person = new Person();person.name("angelababy");person.sex("girl");person.age(18);ctx.write(person);//发送对象,不用序列化,
            ctx.flush();}// • 从服务器接收到数据后调用
    @Overrideprotected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg)throws Exception {System.out.println("client 读取server数据..");// 服务端返回消息后ByteBuf buf = (ByteBuf) msg;byte[] req = new byte[buf.readableBytes()];buf.readBytes(req);String body = new String(req, "UTF-8");System.out.println("服务端数据为 :" + body);}// • 发生异常时被调用
    @Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception {System.out.println("client exceptionCaught..");// 释放资源
        ctx.close();}
}class Person implements Serializable {public static final long serialVersionUID = 1L;public String name;public String sex;public int age;
}

package cn.itcast_03_netty.sendobject.coder;import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;import cn.itcast_03_netty.sendobject.bean.Person;/*** 序列化* 将object转换成Byte[]* @author wilson**/
public class PersonEncoder extends MessageToByteEncoder<Person> {//MessageToByteEncoder继承outbandler
 @Overrideprotected void encode(ChannelHandlerContext ctx, Person msg, ByteBuf out) throws Exception {//工具类:将object转换为byte[]System.out.println("PersonEncoder--out");byte[] datas = objectToByte(msg);out.writeBytes(datas);ctx.flush();}/*** 使用IO的outputstream流将object转换为byte[]* @param bytes* @return*/public 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;}
}

服务端:

package cn.itcast_03_netty.sendobject.server;import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import cn.itcast_03_netty.sendobject.coder.PersonDecoder;/*** • 配置服务器功能,如线程、端口 • 实现服务器处理程序,它包含业务逻辑,决定当有一个请求连接或接收数据时该做什么* * @author wilson**/
public class EchoServer {private final int port;public EchoServer(int port) {this.port = port;}public void start() throws Exception {EventLoopGroup eventLoopGroup = null;try {//创建ServerBootstrap实例来引导绑定和启动服务器ServerBootstrap serverBootstrap = new ServerBootstrap();//创建NioEventLoopGroup对象来处理事件,如接受新连接、接收数据、写数据等等eventLoopGroup = new NioEventLoopGroup();//指定通道类型为NioServerSocketChannel,一种异步模式,OIO阻塞模式为OioServerSocketChannel//设置InetSocketAddress让服务器监听某个端口已等待客户端连接。serverBootstrap.group(eventLoopGroup).channel(NioServerSocketChannel.class).localAddress("localhost",port).childHandler(new ChannelInitializer<Channel>() {//设置childHandler执行所有的连接请求
                @Overrideprotected void initChannel(Channel ch) throws Exception {//注册解码的handlerch.pipeline().addLast(new PersonDecoder());  //IN1  反序列化//添加一个入站的handler到ChannelPipeline  ch.pipeline().addLast(new EchoServerHandler());   //IN2
                }});// 最后绑定服务器等待直到绑定完成,调用sync()方法会阻塞直到服务器完成绑定,然后服务器等待通道关闭,因为使用sync(),所以关闭操作也会被阻塞。ChannelFuture channelFuture = serverBootstrap.bind().sync();System.out.println("开始监听,端口为:" + channelFuture.channel().localAddress());channelFuture.channel().closeFuture().sync();} finally {eventLoopGroup.shutdownGracefully().sync();}}public static void main(String[] args) throws Exception {new EchoServer(20000).start();}
}

package cn.itcast_03_netty.sendobject.server;import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;import java.io.Serializable;import cn.itcast_03_netty.sendobject.bean.Person;public class EchoServerHandler extends ChannelInboundHandlerAdapter {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception {Person person = (Person) msg;System.out.println(person.name);System.out.println(person.age);System.out.println(person.sex);}@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {System.out.println("server 读取数据完毕..");ctx.flush();//刷新后才将数据发出到SocketChannel
    }@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception {cause.printStackTrace();ctx.close();}}class Person implements Serializable {public static final long serialVersionUID = 1L;public String name;public String sex;public int age;
}

package cn.itcast_03_netty.sendobject.coder;import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;/*** 反序列化* 将Byte[]转换为Object* @author wilson**/
public class PersonDecoder extends ByteToMessageDecoder {@Overrideprotected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {//工具类:将ByteBuf转换为byte[]ByteBufToBytes read = new ByteBufToBytes();byte[] bytes = read.read(in);//工具类:将byte[]转换为objectObject obj = byteToObject(bytes);out.add(obj);}/*** 使用IO的inputstream流将byte[]转换为object* @param bytes* @return*/public 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;}class ByteBufToBytes {/*** 将ByteBuf转换为byte[]* @param datas* @return*/public byte[] read(ByteBuf datas) {byte[] bytes = new byte[datas.readableBytes()];// 创建byte[]datas.readBytes(bytes);// 将ByteBuf转换为byte[]return bytes;}}}

转载于:https://www.cnblogs.com/yaowen/p/9031819.html

hadoop28---netty传对象相关推荐

  1. netty发送对象消息

    前言 通过之前的学习,我们知道使用netty在客户端和服务端之间很容易发送一个文本类的消息,但在实际应用中这肯定是不够用的,像java中使用最多的对象这种形式的数据,在客户端和服务端通信的时候也必然会 ...

  2. 对象存储HTML自定义属性,设置对象属性_对象存储服务 OBS_SDK参考_Node.js_上传对象_华为云...

    开发过程中,您有任何问题可以在github上提交issue,或者在华为云对象存储服务论坛中发帖求助.接口参考文档详细介绍了每个接口的参数和使用方法. 您可以在上传对象时设置对象属性.对象属性包含对象长 ...

  3. 传对象与传串_简单介绍

    <html > <head> <title></title>  <script language="javascript"&g ...

  4. java方法传对象参数_Java方法中的参数太多,第2部分:参数对象

    java方法传对象参数 在上一篇文章中 ,我研究了与方法和构造函数的长参数列表相关的一些问题. 在那篇文章中,我讨论了用自定义类型替换基元和内置类型以提高可读性和类型安全性. 这种方法使方法或构造函数 ...

  5. vue路由传参 params传参不能传对象

    不能传对象,传对象的时候,刷新完数据会丢失 传递的是一个对象 但是: 跳转以后,刷新页面,数据会丢失,所以说不能传对象,会有问题

  6. 06Java第六课 获取输入框内容(传对象,参数,值)

    在上一课中实现了对 按钮被点击的监听,接下来要实现 对输入框内容的获取 由之前的界面中可知,账号和密码在输入框对象中,也就是nameInput和pwdInput对象中.当用户输入了账号和密码并点击按钮 ...

  7. 微信小程序连接oracle数据库,【微信小程序】关于微信小程序中跳转传参数与传对象的解析...

    这篇文章主要介绍了微信小程序 跳转传参数与传对象详解及实例代码的相关资料,需要的朋友可以参考下 微信小程序 跳转传参数 传对象 微信小程序跳转传参 一般都是传字符串到下一页,如果要想传对象怎么办呢? ...

  8. netty Recycler对象回收

    netty Recycler对象回收 相关类与接口 Recycler:对象重复使用 public abstract class Recycler<T> {private static fi ...

  9. springmvc 传对象报400_源码导读:深入理解SpringMVC报400时的流程

    相信很多同学都了解过(或者面试前都会复习过)springMVC的执行流程,如下图: 网图 转载请注明出处:Michael孟良 这里我想细节地理解下springMVC报400(也就是上图第5步拿到Han ...

最新文章

  1. 【PHP】字符串去空格并将每个单词首字母转换成大写de多种解法
  2. [测试]将TestCase整合
  3. Sharepoint学习笔记—ECMAScript对象模型系列-- 7、获取和修改List的Lookup字段
  4. mysql将查到的数据删除_MySQL数据库的基本操作——增、删、改、查
  5. Linux C 函数指针应用---回调函数
  6. python自动导出数据脚本_使用python生成一个导出数据库的bat脚本文件的示例代码...
  7. 关于一道面试题【字符串 '1 + (5 - 2) * 3',怎么算出结果为10,'eval'除外】
  8. 如何在Windows下像Mac一样优雅开发
  9. OPPO Reno6 6Pro刷root强解BL锁 oppo reno6 Root教程
  10. 关于STM32的编码器计数及溢出处理调试总结
  11. 苹果iOS捷径(快捷指令)自动填写表单
  12. Python实现视频转 gif 动图
  13. 游戏直播的下一站在哪?战旗TV开启线上线下联动
  14. L1正则化与稀疏性、L1正则化不可导问题
  15. shell脚本:exit 0 和 exit 1有什么区别?他们和return不同,return是关键字,exit是一个shell函数
  16. Lock和Rlock
  17. MySQL基础之多表查询
  18. 前端入门css学习笔记(十一)-----溢出属性之空余空间
  19. 小学计算机网络教室上机制度,网络教室上机登记制度
  20. sbm matlab,超效率sbm模型matlab-如何用matlab估计空间杜宾模型

热门文章

  1. python ---Pandas时间序列:生成指定范围的日期
  2. 洛谷P3807 【模板】卢卡斯定理exgcd
  3. bzoj 4753: [Jsoi2016]最佳团体
  4. Openjudge2729 Blah数集(单调队列)
  5. Linux(Ubuntu)下MySQL的安装与配置
  6. shell脚本编程-结构化命令2-for命令
  7. Grails with ATS Transformation tutorial with a demo example
  8. leetcode算法题--骑士拨号器
  9. 计算机基础知识应用文档,计算机基础知识与应用
  10. c语言程序设计实验教学,C语言程序设计实验教学改革研究