Netty-java序列化对象

首先是对象OrderInfoReq,客户端发送服务器端的对象消息。然后是服务器响应客户端的响应消息对象。最后是基于Netty的对象传输

import java.io.Serializable;
/**
 * @FileName OrderRequest.java
 * @Description: 客户端请求消息实体
 *
 * @Date 2016年3月5日 
 * @author Administroter
 * @version 1.0
 * 
 */
public class OrderInfoReq implements Serializable{
 
 private static final long serialVersionUID = 1L;
 //订单编号
 private String orderId;
 //用户
 private String userName;
 //商品名称
 private String goodsName;
 //电话
 private String phone;
 //地址
 private String address;
 public String getOrderId() {
  return orderId;
 }
 public void setOrderId(String orderId) {
  this.orderId = orderId;
 }
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 public String getGoodsName() {
  return goodsName;
 }
 public void setGoodsName(String goodsName) {
  this.goodsName = goodsName;
 }
 public String getPhone() {
  return phone;
 }
 public void setPhone(String phone) {
  this.phone = phone;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
 public String toString(){
  return "[orderId="+orderId+",userName="+userName+",goodsName="+goodsName+",phone="+phone+",address="+address+"]";
 }
}
import java.io.Serializable;
/**
 * @FileName Order.java
 * @Description: 服务器端响应消息实体
 *
 * @Date 2016年3月5日 
 * @author Administroter
 * @version 1.0
 * 
 */
public class OrderInfoResp implements Serializable{
 private static final long serialVersionUID = 1L;
 //订单编号
 private String orderId;
 //响应结果,0标识订购成功
 private String respId;
 //一些描述信息
 private String desc;
 public String getOrderId() {
  return orderId;
 }
 public void setOrderId(String orderId) {
  this.orderId = orderId;
 }
 public String getRespId() {
  return respId;
 }
 public void setRespId(String respId) {
  this.respId = respId;
 }
 public String getDesc() {
  return desc;
 }
 public void setDesc(String desc) {
  this.desc = desc;
 }
 public String toString(){
  return "[orderId="+orderId+",respId="+respId+",desc="+desc+"]";
 }
}
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 io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
/**
 * @FileName OrederClient.java
 * @Description:
 *
 * @Date 2016年3月5日
 * @author Administroter
 * @version 1.0
 * 
 */
public class OrderClient {
 public void connect(int port, String host) throws Exception {
  // 配置客户端NIO线程组
  EventLoopGroup group = new NioEventLoopGroup();
  try {
   // 客户端辅助启动类
   Bootstrap b = new Bootstrap();
   b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
     .handler(new ChannelInitializer<SocketChannel>() {
      public void initChannel(SocketChannel ch) throws Exception {
       ch.pipeline().addLast(new ObjectDecoder(1024,
         ClassResolvers.cacheDisabled(this.getClass().getClassLoader())));
       ch.pipeline().addLast(new ObjectEncoder());
       ch.pipeline().addLast(new OrderClientHandler());
      }
     });
   // 发起异步连接操作
   ChannelFuture f = b.connect(host, port).sync();
   // 当代客户端链路关闭
   f.channel().closeFuture().sync();
  } finally {
   // 优雅退出,释放NIO线程组
   group.shutdownGracefully();
  }
 }
 /**
  * @param args
  * @throws Exception
  */
 public static void main(String[] args) throws Exception {
  int port = 8080;
  if (args != null && args.length > 0) {
   try {
    port = Integer.valueOf(args[0]);
   } catch (NumberFormatException e) {
    // 采用默认值
   }
  }
  new OrderClient().connect(port, "127.0.0.1");
 }
}
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import java.util.logging.Logger;
import com.lxf.netty.dome.TimeClientHandler;
/**
 * @FileName OrderClientHandler.java
 * @Description: 
 *
 * @Date 2016年3月5日 
 * @author Administroter
 * @version 1.0
 * 
 */
public class OrderClientHandler extends ChannelHandlerAdapter{
 private static final Logger logger = Logger.getLogger(TimeClientHandler.class.getName());
 /**
  * TCP链路建立成功后,调用这个方法发送查询指令给服务器
  */
 @Override
 public void channelActive(ChannelHandlerContext ctx) {
  for (int i = 0; i < 5; i++) {
   ctx.writeAndFlush(sendRequest(i));
  }
  ctx.flush();
 }
 
 private OrderInfoReq sendRequest(int i){
  OrderInfoReq orderInfo = new OrderInfoReq();
  orderInfo.setOrderId("2016030500"+String.valueOf(i));
  orderInfo.setUserName("张三");
  orderInfo.setGoodsName("海尔冰箱");
  orderInfo.setPhone("15246854685");
  orderInfo.setAddress("深圳市南山科技园高新南一道中科大厦");
  return orderInfo;
 }
 
 /**
  * 服务器你响应结果后调用这个方法,获取服务器响应的结果
  */
 @Override
 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  System.out.println("服务器响应的信息:" + msg);
 }
 
 
 /**
  * 链路建立失败,释放资源
  */
 @Override
 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
  // 释放资源
  logger.warning("Unexpected exception from downstream : " + cause.getMessage());
  ctx.close();
 }
}
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;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
/**
 * @FileName OrderServer.java
 * @Description: 
 *
 * @Date 2016年3月5日 
 * @author Administroter
 * @version 1.0
 * 
 */
public class OrderServer {
 //作为对象最大序列化后byte数组长度的大小
 private int byteLength = 1024*1024;
 
 public void bind(int port) throws Exception {
  // 配置服务端的NIO线程组
  EventLoopGroup bossGroup = new NioEventLoopGroup();
  EventLoopGroup workerGroup = new NioEventLoopGroup();
  try {
   ServerBootstrap b = new ServerBootstrap();
   b.group(bossGroup, workerGroup)
    .channel(NioServerSocketChannel.class)
    .option(ChannelOption.SO_BACKLOG, 100)
    .handler(new LoggingHandler(LogLevel.INFO))
    .childHandler(new ChildChannelHandler());
   ChannelFuture f = b.bind(port).sync();
   // 等待服务端监听端口关闭
   f.channel().closeFuture().sync();
  } finally {
   // 优雅退出,释放线程池资源
   bossGroup.shutdownGracefully();
   workerGroup.shutdownGracefully();
  }
 }
 
 
 private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
  @Override
  protected void initChannel(SocketChannel arg0) throws Exception {
   //添加解码器,负责对实现了序列化的实体对象进行解码
   arg0.pipeline().addLast(new ObjectDecoder(byteLength , 
     ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
   //将在消息发送的时候自动将实现了序列化的实体对象进行编码
   arg0.pipeline().addLast(new ObjectEncoder());
   arg0.pipeline().addLast(new OrderServerHandler());
  }
 }
 
 /**
  * @param args
  * @throws Exception
  */
 public static void main(String[] args) throws Exception {
  int port = 8080;
  if (args != null && args.length > 0) {
   try {
    port = Integer.valueOf(args[0]);
   } catch (NumberFormatException e) {
    // 采用默认值
   }
  }
  new OrderServer().bind(port);
 }
}
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
/**
 * @FileName OrderServerHandler.java
 * @Description: 
 *
 * @Date 2016年3月5日 
 * @author Administroter
 * @version 1.0
 * 
 */
public class OrderServerHandler extends ChannelHandlerAdapter{
 
 int counter = 0;
 
 @Override
 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  OrderInfoReq orderInfo = (OrderInfoReq)msg;
  if ("张三".equals(orderInfo.getUserName())) {
   System.out.println("客户端的请求消息:"+orderInfo.toString());
   ctx.writeAndFlush(responseInfo(orderInfo.getOrderId()));
  }
 }
 /**
  * @Title: responseInfo 
  * @Description:响应客户端的消息
  * @param orderId
  * @return 
  * @author Administroter
  * @date 2016年3月5日
  */
 private OrderInfoResp responseInfo(String orderId){
  OrderInfoResp response = new OrderInfoResp();
  response.setOrderId(orderId);
  response.setRespId("0");
  response.setDesc("亲!你的第"+ ++counter +"订单,订购成功。");
  return response;
 }
 @Override
 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
  cause.printStackTrace();
  ctx.close();
 }
}

你可能感兴趣的:(netty,objectdecoder,Netty传递对象,ObjectEncoder,Netty序列化对象)