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,客户端成功连接服务器后就会被执行
@Override
protected void initChannel(SocketChannel ch)
throws Exception {
// 注册编码的handler
ch.pipeline().addLast(new PersonEncoder()); //out
//注册处理消息的handler
ch.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> {
// 客户端连接服务器后被调用
@Override
public 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();
} // • 从服务器接收到数据后调用
@Override
protected 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);
} // • 发生异常时被调用
@Override
public 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 @Override
protected 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执行所有的连接请求
@Override
protected void initChannel(Channel ch) throws Exception {
//注册解码的handler
ch.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 { @Override
public 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);
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("server 读取数据完毕..");
ctx.flush();//刷新后才将数据发出到SocketChannel
} @Override
public 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 {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
//工具类:将ByteBuf转换为byte[]
ByteBufToBytes read = new ByteBufToBytes();
byte[] bytes = read.read(in);
//工具类:将byte[]转换为object
Object 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;
}
} }

hadoop28---netty传对象的更多相关文章

  1. Netty轻量级对象池实现分析

    什么是对象池技术?对象池应用在哪些地方? 对象池其实就是缓存一些对象从而避免大量创建同一个类型的对象,类似线程池的概念.对象池缓存了一些已经创建好的对象,避免需要时才创建对象,同时限制了实例的个数.池 ...

  2. onclick传对象

    用onclick传对象的时候,用jquery无法进行操作 onclick=(this) 接收到参数后只需要转化一下 console.log($(obj).html());

  3. 8.Netty发送对象

    1.Netty发送对象简介: Netty中,通讯的双方建立连接后,会把数据按照ByteBuf的方式进行传输,例如http协议中,就是通过HttpRequestDecoder对 ByteBuf数 据流进 ...

  4. Netty(7)-传对象

    改造timer,即客户端与服务端建立连接后,服务端主动向客户端发送当前时间. server: ch.pipeline().addLast(new TimeEncoder()); ch.pipeline ...

  5. delphi客户端调服务器端的java webservice如何在参数中传对象? 转

    我试过java返回一个对象到delphi端没问题,可反过来,delphi通过参数传一个对象到java,java端得到的对象值变为空,不知道是不是delphi这边设置或者对象注册方面有问题,究竟该怎么解 ...

  6. 动态调用WebService(传对象返回接受对象)

    基础属性//客户端代理服务命名空间,可以设置成需要的值. string ns = string.Format("WindowsForms"); private Assembly a ...

  7. netty的对象传输

    pom <!-- https://mvnrepository.com/artifact/io.netty/netty-all --> <dependency> <grou ...

  8. tp5依赖注入(自动实例化):解决了像类中的方法传对象的问题

    app\index\Demo1.php namespace app\index\controller; /* 容器与依赖注入的原理 ----------------------------- 1.任何 ...

  9. 微信小程序 navigateTo 传对象参数

    当微信小程序navigateTo传入参数是个object时,请使用JSON.strtingify将object转化为字符串,代码如下: wx.navigateTo({ url: '../sendChe ...

随机推荐

  1. openldap+php-ldap操作

    一.基础知识首先,如果您对LDAP 不认识,建议先看看[原]LDAP服务介绍一文.本文以Linux 下常用的OpenLDAP为例说明.LDAP 以数方式存放数据,每个节点可存放属性或作为下面节点的父节 ...

  2. 【Cloud Foundry】Cloud Foundry学习(四)——Service

    在阅读的过程中有不论什么问题,欢迎一起交流 邮箱:1494713801@qq.com    QQ:1494713801 Services:Cloud Foundry的Service模块从源码控制上看就 ...

  3. NSTimer的循环引用

    在日常开发中想到会引起循环引用的一般比较容易想起的是 1.delegate 2.block 今天要说的就是另外一个,NSTimer 这个比较容易会被忽略掉 简单的说就是创建timer为成员变量的时候t ...

  4. 到底什么是hash

    1.什么是hash算法 Hash(散列.杂凑)算法,是把任意长度的输入通过特定的算法变换成固定长度的输出,输出的值就是hash值.这个特定的算法就叫hash算法,hash算法并不是一个固定不变的算法. ...

  5. android 性能測试CTS篇

    CTS介绍 一.CTS简单介绍 CTS 全称Compatibility Test Suite兼容性測试工具. 当电子产品开发出来.并定制了自己的Android系统后,必需要通过最新的CTS检測.以保证 ...

  6. iOS 开发之--打测试包的时候报错的解决方法

    在打测试包的时候,一直出现一个报错,解决方法如下: 方法一: 描述文件所在目录是:~/Library/MobileDevice/Provisioning\ Profiles/,可以直接前往文件夹,把所 ...

  7. python 之 内置函数大全

    一.罗列全部的内置函数 戳:https://docs.python.org/2/library/functions.html 二.range.xrange(迭代器) 无论是range()还是xrang ...

  8. bnuoj 34990(后缀数组 或 hash+二分)

    后缀数组倍增算法超时,听说用3DC可以勉强过,不愿写了,直接用hash+二分求出log(n)的时间查询两个字符串之间的任意两个位置的最长前缀. 我自己在想hash的时候一直在考虑hash成数值时MOD ...

  9. 将坐标转化为与X轴正半轴夹角模板

    //还需加PI 和 mabs 函数 double chg(double x,double y) { double tmps; )<1e-) { ) tmps=90.0; else tmps=27 ...

  10. 《JavaScript高级程序设计》读书笔记1--HTTP头部信息

    优秀的书籍常读常新 ----------------------------------------- 在发送XHR请求的同时,还会发送如下头部信息: --Accept: 浏览器能够处理的内容类型 - ...