ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] # 简介 Netty中,通讯的双方建立连接后,会把数据按照ByteBuf的方式进行传输,例如http协议中,就是通过HttpRequestDecoder对ByteBuf数据流进行处理,转换成http的对象。基于这个思路,可自定义一种通讯协议:Server和客户端直接传输java对象。 实现的原理是通过Encoder把java对象转换成ByteBuf流进行传输,通过Decoder把ByteBuf转换成java对象进行处理,处理逻辑如下图所示: ![](https://box.kancloud.cn/fad95918367e9ac7bf22c8e2a02b681b_932x296.png) # bean包 **Person类** ~~~ package com.bean; 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; } } ~~~ # coder包 **PersonEncoder** ~~~ package com.coder; import com.bean.Person; import com.utils.ByteObjConverter; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; /** * 序列化 * 将object转换成Byte[] */ public class PersonEncoder extends MessageToByteEncoder<Person> { @Override protected void encode(ChannelHandlerContext ctx, Person msg, ByteBuf out) throws Exception { //工具类:将object转换为byte[] byte[] datas = ByteObjConverter.objectToByte(msg); out.writeBytes(datas); ctx.flush(); } } ~~~ **PersonDecoder** ~~~ package com.coder; import com.utils.ByteBufToBytes; import com.utils.ByteObjConverter; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import java.util.List; 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 = ByteObjConverter.byteToObject(bytes); //out中的obj将被一个个fireChannelRead到下一个InBoundHandler中 out.add(obj); } } ~~~ # nettyServer包 **EchoServer** ~~~ package com.nettyServer; import com.coder.PersonDecoder; 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; 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(); } } ~~~ **EchoServerHandler** ~~~ package com.nettyServer; import com.bean.Person; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class EchoServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { Person person = (Person) msg; System.out.println(person.getName()); System.out.println(person.getAge()); System.out.println(person.getSex()); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { System.out.println("server 读取数据完毕.."); ctx.flush(); //flush后才将数据发出到SocketChannel } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } } ~~~ # nettyClient包 **EchoClient** ~~~ package com.nettyClient; import com.coder.PersonEncoder; 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; 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(); } } ~~~ **EchoClientHandler** ~~~ package com.nettyClient; import com.bean.Person; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> { // 客户端连接服务器后被调用 @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { Person person = new Person(); person.setName("angelababy"); person.setSex("girl"); person.setAge(18); ctx.write(person); ctx.flush(); ctx.close(); } // • 从服务器接收到数据后调用 @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); // ctx.close(); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { } // • 发生异常时被调用 @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("client exceptionCaught.."); // 释放资源 ctx.close(); } } ~~~ # utils包 **ByteBufToBytes** ~~~ package com.utils; import io.netty.buffer.ByteBuf; public 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; } } ~~~ **ByteObjConverter** ~~~ package com.utils; import com.bean.Person; import java.io.*; public class ByteObjConverter { /** * 使用IO的inputstream流将byte[]转换为object * @param bytes * @return */ 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; } /** * 使用IO的outputstream流将object转换为byte[] */ 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; } } ~~~