`
shihuan830619
  • 浏览: 580111 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Netty中Marshalling编解码应用

阅读更多
项目结构图:


SubscribeReq.java文件内容如下:
package com.shihuan.netty.codec.marshalling.pojo;

import java.io.Serializable;

public class SubscribeReq implements Serializable {

	private int subReqID;

    private String userName;

    private String productName;

    private String phoneNumber;

    private String address;

	public final int getSubReqID() {
		return subReqID;
	}

	public final void setSubReqID(int subReqID) {
		this.subReqID = subReqID;
	}

	public final String getUserName() {
		return userName;
	}

	public final void setUserName(String userName) {
		this.userName = userName;
	}

	public final String getProductName() {
		return productName;
	}

	public final void setProductName(String productName) {
		this.productName = productName;
	}

	public final String getPhoneNumber() {
		return phoneNumber;
	}

	public final void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

	public final String getAddress() {
		return address;
	}

	public final void setAddress(String address) {
		this.address = address;
	}

	/*
     * (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
	return "SubscribeReq [subReqID=" + subReqID + ", userName=" + userName
		+ ", productName=" + productName + ", phoneNumber="
		+ phoneNumber + ", address=" + address + "]";
    }
	
}


SubscribeResp.java文件内容如下:
package com.shihuan.netty.codec.marshalling.pojo;

import java.io.Serializable;

public class SubscribeResp implements Serializable {

	private int subReqID;

    private int respCode;

    private String desc;

	public final int getSubReqID() {
		return subReqID;
	}

	public final void setSubReqID(int subReqID) {
		this.subReqID = subReqID;
	}

	public final int getRespCode() {
		return respCode;
	}

	public final void setRespCode(int respCode) {
		this.respCode = respCode;
	}

	public final String getDesc() {
		return desc;
	}

	public final void setDesc(String desc) {
		this.desc = desc;
	}
	
	/*
     * (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
	return "SubscribeResp [subReqID=" + subReqID + ", respCode=" + respCode
		+ ", desc=" + desc + "]";
    }
	
}


MarshallingCodeCFactory.java文件内容如下:
package com.shihuan.netty.codec.marshalling.server;

import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;

import io.netty.handler.codec.marshalling.DefaultMarshallerProvider;
import io.netty.handler.codec.marshalling.DefaultUnmarshallerProvider;
import io.netty.handler.codec.marshalling.MarshallerProvider;
import io.netty.handler.codec.marshalling.MarshallingDecoder;
import io.netty.handler.codec.marshalling.MarshallingEncoder;
import io.netty.handler.codec.marshalling.UnmarshallerProvider;

public final class MarshallingCodeCFactory {

	/**
	 * 创建Jboss Marshalling解码器MarshallingDecoder
	 */
	public static MarshallingDecoder buildMarshallingDecoder() {
		final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
		final MarshallingConfiguration configuration = new MarshallingConfiguration();
		configuration.setVersion(5);
		UnmarshallerProvider provider = new DefaultUnmarshallerProvider(marshallerFactory, configuration);
		MarshallingDecoder decoder = new MarshallingDecoder(provider, 1024);
		return decoder;
	}

	/**
	 * 创建Jboss Marshalling编码器MarshallingEncoder
	 */
	public static MarshallingEncoder buildMarshallingEncoder() {
		final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
		final MarshallingConfiguration configuration = new MarshallingConfiguration();
		configuration.setVersion(5);
		MarshallerProvider provider = new DefaultMarshallerProvider(marshallerFactory, configuration);
		MarshallingEncoder encoder = new MarshallingEncoder(provider);
		return encoder;
	}
	
}


SubReqServerHandler.java文件内容如下:
package com.shihuan.netty.codec.marshalling.server;

import com.shihuan.netty.codec.marshalling.pojo.SubscribeReq;
import com.shihuan.netty.codec.marshalling.pojo.SubscribeResp;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

@Sharable
public class SubReqServerHandler extends ChannelHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		SubscribeReq req = (SubscribeReq) msg;
		if ("Lilinfeng".equalsIgnoreCase(req.getUserName())) {
			System.out.println("Service accept client subscrib req : [" + req.toString() + "]");
			ctx.writeAndFlush(resp(req.getSubReqID()));
		}
	}

	private SubscribeResp resp(int subReqID) {
		SubscribeResp resp = new SubscribeResp();
		resp.setSubReqID(subReqID);
		resp.setRespCode(0);
		resp.setDesc("Netty book order succeed, 3 days later, sent to the designated address");
		return resp;
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace();
		ctx.close();// 发生异常,关闭链路
	}
	
}


SubReqServer.java文件内容如下:
package com.shihuan.netty.codec.marshalling.server;

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.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class SubReqServer {

	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 ChannelInitializer<SocketChannel>() {
				@Override
				public void initChannel(SocketChannel ch) {
					ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
					ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
					ch.pipeline().addLast(new SubReqServerHandler());
				}
			});

			// 绑定端口,同步等待成功
			ChannelFuture f = b.bind(port).sync();

			// 等待服务端监听端口关闭
			f.channel().closeFuture().sync();
		} finally {
			// 优雅退出,释放线程池资源
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
	
	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 SubReqServer().bind(port);
	}
	
}


SubReqClientHandler.java文件内容如下:
package com.shihuan.netty.codec.marshalling.client;

import com.shihuan.netty.codec.marshalling.pojo.SubscribeReq;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class SubReqClientHandler extends ChannelHandlerAdapter {

	/**
	 * Creates a client-side handler.
	 */
	public SubReqClientHandler() {
		
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) {
		for (int i=0; i<10; i++) {
			ctx.write(subReq(i));
		}
		ctx.flush();
	}

	private SubscribeReq subReq(int i) {
		SubscribeReq req = new SubscribeReq();
		req.setAddress("NanJing YuHuaTai");
		req.setPhoneNumber("136xxxxxxxxx");
		req.setProductName("Netty Book For Marshalling");
		req.setSubReqID(i);
		req.setUserName("Lilinfeng");
		return req;
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println("Receive server response : [" + msg + "]");
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace();
		ctx.close();
	}
	
}


SubReqClient.java文件内容如下:
package com.shihuan.netty.codec.marshalling.client;

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 com.shihuan.netty.codec.marshalling.server.MarshallingCodeCFactory;

public class SubReqClient {

	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>() {
				@Override
				public void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
					ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
					ch.pipeline().addLast(new SubReqClientHandler());
				}
			});

			// 发起异步连接操作
			ChannelFuture f = b.connect(host, port).sync();

			// 当代客户端链路关闭
			f.channel().closeFuture().sync();
		} finally {
			// 优雅退出,释放NIO线程组
			group.shutdownGracefully();
		}
	}
	
	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 SubReqClient().connect(port, "127.0.0.1");
	}
	
}


【注】:marshalling.rar文件是可运行的源代码。在Netty中通过应用Jboss Marshalling的编解码后既压缩了传输对象的体积大小又解决了传输过程中半包粘包的问题。
  • 大小: 32.7 KB
分享到:
评论

相关推荐

    Netty中Marshalling编解码自定义栈应用

    本文将深入探讨 Marshalling 编解码器在 Netty 中的应用及其自定义实现。 Marshalling 是一种序列化技术,它能够将 Java 对象转换为字节流,便于在网络中传输,同时也可以将字节流恢复为原来的对象。在 Netty 中,...

    Netty的技术的总结(Marshalling编解码,tcp的拆包粘包,webservice),包括新手入门源码,注释清楚,绝对物超所值

    **Marshalling编解码**:Marshalling是将对象序列化成二进制的过程,便于在网络中传输。在Netty中,MarshallingDecoder和MarshallingEncoder是用于处理这种序列化和反序列化的组件。它们允许我们将Java对象转换为...

    使用Netty进行编解码的操作过程详解

    为了解决这些问题,需要使用专门的编解码框架,如Google的Protobuf、Facebok的Thrift、Jboss Marshalling、MessagePack等。 MessagePack是一个高效的二进制序列化框架,它像JSON一样支持不同的语言间的数据交换,...

    netty权威指南第2版

    第9章 JBoss Marshalling 编解码 第10章 HTTP协议开发应用 第11章 WebSocket协议开发 第12章 私有协议栈开发 第13章 服务端创建 第14章 客户端创建 第15章 ByteBuf 和相关辅助类 第16章 Channel 和Unsafe 第17章 ...

    netty权威指南第二版,包含netty-4.1.22.Final,messagepack,marshalling jar包

    在Netty中,可以通过集成MessagePack编解码器来实现高效的序列化和反序列化。 4. **Marshalling**:Marshalling用于将Java对象转换为字节流,方便在网络中传输或存储。在分布式系统中,对象的序列化和反序列化是...

    Netty权威指南(第2版)(李林峰)-书签目录-完整版.zip

    第9 章 JBoss Marshalling 编解码...... 143 第10 章 HTTP 协议开发应用...... 154 第11 章 WebSocket 协议开发...... 203 第12 章 私有协议栈开发...... 221 第13 章 服务端创建......

    nett权威指南,学习整理的demo代码

    netty学习简单案列demo记录 ...7.netty权威指南中的私有协议栈开发章节,内容包含protocol编解码、心跳、断线重连等。marshalling编解码未走通。 - netty-protocalstack 8.netty+zk实现简单rpc框架 netty-demo-rpc目录

    netty-4.1.25.Final实用例子

    这是使用netty-4.1.25.Final编写的常用例子,代码全部可以执行,用eclipse打开,包括以下几点: ...4.jboss的Marshalling编解码例子 5.传输对象例子 6.protobuf编解码例子(和简易教程) 7.断线重连例子 8.同步调用方法

    marshalling 1.3.0

    jboss marshalling 1.3.0 Java 对象序列化 netty 编解码

    Netty4&5源码编译所需jar包

    9. **jzlib-1.1.3.jar**:一个纯Java实现的ZLIB压缩库,用于数据压缩和解压缩,可能在Netty的压缩编码解码中发挥作用。 10. **commons-logging-1.1.1.jar**:Apache Commons Logging,一个轻量级的日志接口,允许在...

    Netty权威指南

    Netty ...中级篇:编解码技术和常用的序列化框架(protobuf /java/Marshalling) 高级篇:Http协议开发; Netty 协议栈开发(数据结构定义,消息编解码,握手安全认证,心跳检测等); WebSocket等

    基于Java和Netty实现的联机版坦克大战游戏.zip

    使用Marshalling作为编解码技术 3. 游戏界面使用java自带的swing与awt进行编写 4. 使用Spring的依赖注入与java的反射机制简化了消息类型的判定 5. 使用Mysql数据库 6. 使用log4j记录日志 详细介绍参考:...

    基于Java+Netty+MySQL实现联机版坦克大战【100011266】

    使用Marshalling作为编解码技术 游戏界面使用java自带的swing与awt进行编写 使用Spring的依赖注入与java的反射机制简化了消息类型的判定 使用Mysql数据库 使用log4j记录日志 实现功能: 人机对战 多玩家开房间对战 ...

    第八章:附带的ChannelHandler和Codec.pdf

    第八章聚焦于Netty中的附加ChannelHandler和Codec,这些组件对于构建高效、安全的网络应用程序至关重要。本章主要讨论了以下几个核心知识点: 1. **使用SSL/TLS创建安全的Netty程序**:SSL(Secure Socket Layer)...

    java版飞机大战源码-TankBattle:基于Netty的联机版坦克大战

    使用Marshalling作为编解码技术 游戏界面使用java自带的swing与awt进行编写 使用Spring的依赖注入与java的反射机制简化了消息类型的判定 使用Mysql数据库 使用log4j记录日志 实现功能: 人机对战 多玩家开房间对战 ...

Global site tag (gtag.js) - Google Analytics