博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Netty4.x中文教程系列(四) 对象传输
阅读量:4645 次
发布时间:2019-06-09

本文共 8194 字,大约阅读时间需要 27 分钟。

 

 Netty4.x中文教程系列(四)  对象传输 

  我们在使用netty的过程中肯定会遇到传输对象的情况,Netty4通过ObjectEncoder和ObjectDecoder来支持。

  首先我们定义一个User对象,一定要实现Serializable接口:

package mjorcen.netty.object;import java.io.Serializable;/** * User: hupeng Date: 14-6-3 Time: 上午1:31 */public class User implements Serializable {    private int id;    private String name;    private String cardNo;    private String description;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getCardNo() {        return cardNo;    }    public void setCardNo(String cardNo) {        this.cardNo = cardNo;    }    public String getDescription() {        return description;    }    public void setDescription(String description) {        this.description = description;    }    @Override    public String toString() {        return "User{" + "id=" + id + ", name='" + name + '\'' + ", cardNo='"                + cardNo + '\'' + ", description='" + description + '\'' + '}';    }}

服务端和客户端里,我们自定义的Handler实现如下:

server

package mjorcen.netty.object;import io.netty.bootstrap.ServerBootstrap;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.NioServerSocketChannel;import io.netty.handler.codec.serialization.ClassResolvers;import io.netty.handler.codec.serialization.ObjectDecoder;import io.netty.handler.codec.serialization.ObjectEncoder;public class ObjectTranferServer {    private final int port;    public ObjectTranferServer(int port) {        this.port = port;    }    public void run() throws Exception {        EventLoopGroup bossGroup = new NioEventLoopGroup(1);        EventLoopGroup workerGroup = new NioEventLoopGroup();        try {            ServerBootstrap b = new ServerBootstrap();            b.group(bossGroup, workerGroup)                    .channel(NioServerSocketChannel.class)                    .childHandler(new ChannelInitializer
() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( new ObjectEncoder(), new ObjectDecoder(Integer.MAX_VALUE,ClassResolvers.cacheDisabled(null)), new ObjectTransferServerHandler()); } }); // Bind and start to accept incoming connections. b.bind(port).sync().channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { int port; if (args.length > 0) { port = Integer.parseInt(args[0]); } else { port = 11000; } new ObjectTranferServer(port).run(); }}

serverHandler

package mjorcen.netty.object;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;import java.util.logging.Level;import java.util.logging.Logger;public class ObjectTransferServerHandler extends ChannelInboundHandlerAdapter {    private static final Logger logger = Logger            .getLogger(ObjectTransferServerHandler.class.getName());    @Override    public void channelRead(ChannelHandlerContext ctx, Object msg)            throws Exception {        System.out.println(msg);        ctx.writeAndFlush(msg);    }    // @Override    // public void channelReadComplete(ChannelHandlerContext ctx) throws    // Exception {    // ctx.flush();    // ctx.close();    // }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)            throws Exception {        logger.log(Level.WARNING, "Unexpected exception from downstream.",                cause);        ctx.close();    }}

 

client

package mjorcen.netty.object;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 io.netty.handler.codec.serialization.ClassResolvers;import io.netty.handler.codec.serialization.ObjectDecoder;import io.netty.handler.codec.serialization.ObjectEncoder;public class ObjectTransferClient {    private String host;    private int port;    private int messageSize;    public ObjectTransferClient(String host, int port, int messageSize) {        this.host = host;        this.port = port;        this.messageSize = messageSize;    }    public void run() throws InterruptedException {        Bootstrap bootstrap = new Bootstrap();        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();        try {            bootstrap.group(eventLoopGroup)                    .channel(NioSocketChannel.class)                    .handler(new ChannelInitializer
() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( new ObjectEncoder(), new ObjectDecoder(Integer.MAX_VALUE ,ClassResolvers.cacheDisabled(null)), new ObjectTransferClientHandler(messageSize)); } }); ChannelFuture future = bootstrap.connect(host, port).sync(); future.channel().closeFuture().sync(); } finally { eventLoopGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { final String host = "localhost"; final int port = 11000; final int messageSize = 20; new ObjectTransferClient(host, port, messageSize).run(); }}

clientHandler

package mjorcen.netty.object;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;import java.util.ArrayList;import java.util.List;import java.util.logging.Level;import java.util.logging.Logger;public class ObjectTransferClientHandler extends ChannelInboundHandlerAdapter {    private static final Logger logger = Logger            .getLogger(ObjectTransferClientHandler.class.getName());    private final List
message; /** * Creates a client-side handler. */ public ObjectTransferClientHandler(int messageSize) { if (messageSize <= 0) { throw new IllegalArgumentException("firstMessageSize: " + messageSize); } message = new ArrayList
(messageSize); for (int i = 0; i < messageSize; i++) { User user = new User(); user.setId(i); user.setCardNo("420000" + i); user.setName("hu" + i); user.setDescription("你觉得这样好吗??真的好吗" + i); message.add(user); } } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { // Send the message to Server super.channelActive(ctx); ctx.writeAndFlush(message); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // you can use the Object from Server here System.out.println(msg); ctx.close(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.log(Level.WARNING, "Unexpected exception from downstream.", cause); ctx.close(); }}

 

简单梳理一下思路:

  1. 通过Netty传递,都需要基于流,以ChannelBuffer的形式传递。所以,Object -> ChannelBuffer.
  2. Netty提供了转换工具,需要我们配置到Handler。
  3. 样例从客户端 -> 服务端,单向发消息,所以在客户端配置了编码,服务端解码。如果双向收发,则需要全部配置Encoder和Decoder。

  这里需要注意,注册到Server的Handler是有顺序的,如果你颠倒一下注册顺序:

  结果就是,会先进入我们自己的业务,再进行解码。这自然是不行的,会强转失败。至此,你应该会用Netty传递对象了吧。

 

转载于:https://www.cnblogs.com/mjorcen/p/3994569.html

你可能感兴趣的文章
选择排序
查看>>
怎样设计接口?
查看>>
Rabbitmq 加入用户訪控制台(guest无法登陆控制台问题)
查看>>
数据挖掘十大经典算法
查看>>
MDI窗体
查看>>
两个有序数组中找中位数或者第K大的元素
查看>>
使用 SP_OAXXX 创建文件夹,注意区别于 xp_cmdshell --mkdir xxx
查看>>
2. Probability
查看>>
Linux下配置两个jboss 5.1
查看>>
联系人的侧边字母索引ListView 将手机通讯录姓名通过首字母排序。
查看>>
vim 光标后退
查看>>
vim 的寄存器
查看>>
SDWebImage源码刨根问底
查看>>
ASP.NET 状态的传递和保存
查看>>
C++简单程序设计-2
查看>>
ZendFramework第二章
查看>>
JavaScript ArrayBuffer浅析
查看>>
springMVC用法 以及一个简单的基于springMVC hibernate spring的配置
查看>>
bzoj 1726: [Usaco2006 Nov]Roadblocks第二短路【dijskstra】
查看>>
bzoj 3624: [Apio2008]免费道路【生成树+贪心】
查看>>