Netty实战-对象编解码,Netty对象网络传递

书籍推荐:

       实例代码 : http://download.csdn.net/detail/jiangtao_st/7677503

  1. Server端代码
    <span style="font-size:12px;">/**
     * 
     * <p>
     * 	Netty Server Simple
     * </p>
     * 
     * LineBasedFrameDecoder + 消息中得换行符
     * 	
     * @author 卓轩
     * @创建时间:2014年7月7日
     * @version: V1.0
     */
    
    public class NettyServer {
    	
    	private final int port = 8989;
    	
    	@Test
    	public void nettyServer(){
    		
    		EventLoopGroup bossGroup = new NioEventLoopGroup();
    		EventLoopGroup workerGroup = new NioEventLoopGroup();
    		
    		try {
    			ServerBootstrap serverBootstrap = new ServerBootstrap();
    			serverBootstrap.group(bossGroup,workerGroup)
    				.channel(NioServerSocketChannel.class)
    				.option(ChannelOption.SO_BACKLOG, 1024)
    				.childHandler(new ChildChannelHandler());
    			
    			//绑定端口、同步等待
    			ChannelFuture futrue = serverBootstrap.bind(port).sync();
    			
    			//等待服务监听端口关闭
    			futrue.channel().closeFuture().sync();
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}finally{
    			//退出,释放线程等相关资源
    			bossGroup.shutdownGracefully();
    			workerGroup.shutdownGracefully();
    		}
    
    		
    	}
    
    	private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{
    		@Override
    		protected void initChannel(SocketChannel ch) throws Exception {
    			//ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
    //			
    //			ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
    //			ch.pipeline().addLast(new DelimiterBasedFrameDecoder(2048, delimiter));
    //			
    			//ch.pipeline().addLast(new FixedLengthFrameDecoder(20));
    			ch.pipeline().addLast(new ObjectDecoder(1024*1024,ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
    			ch.pipeline().addLast(new ObjectEncoder());
    			ch.pipeline().addLast(new StringDecoder());
    			ch.pipeline().addLast(new UserRespServerHandler());
    		}
    	}
    	
    	
    }</span>
  2. Client端代码
    <span style="font-size:12px;">/**
     * 
     * <p>
     * 	NettyClient  实现
     * </p>
     * 
     * @author 卓轩
     * @创建时间:2014年7月7日
     * @version: V1.0
     */
    public class NettyClient {
    
    	
    	
    	public void connect(int port,String host){
    		
    		EventLoopGroup group = new NioEventLoopGroup();
    		
    		try {
    			Bootstrap bootstrap = new Bootstrap();
    			bootstrap.group(group)
    			.channel(NioSocketChannel.class)
    			.option(ChannelOption.TCP_NODELAY, true)
    			.handler(new ChannelInitializer<SocketChannel>() {
    
    				@Override
    				protected void initChannel(SocketChannel ch) throws Exception {
    					
    					ch.pipeline().addLast(new ObjectDecoder(1024,ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
    					ch.pipeline().addLast(new ObjectEncoder());
    					
    					ch.pipeline().addLast(new StringDecoder());
    					ch.pipeline().addLast(new UserQueryClientHandler());
    				}
    			});
    			//发起异步链接操作
    			ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
    			
    			channelFuture.channel().closeFuture().sync();
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}finally{
    			//关闭,释放线程资源
    			group.shutdownGracefully();
    		}
    	}	
    	@Test
    	public void nettyClient(){
    		
    		new NettyClient().connect(8989, "localhost");
    	}
    }</span>
  3. ServerHander 代码
    <span style="font-size:12px;">/**
     * 
     * <p>
     *  用户查询返回
     * </p>
     * 
     * @author 卓轩
     * @创建时间:2014年7月7日
     * @version: V1.0
     */
    public class UserRespServerHandler extends ChannelInboundHandlerAdapter {
    
    
    	@Override
    	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    		
    		UserQuery userQuery = (UserQuery) msg;
    		
    		System.out.println("收到来自客户端的查询请求:"+ String.valueOf(userQuery));
    		
    		if(userQuery != null && userQuery.getUserId()!= 0){
    			UserDO userDO = getUserById(userQuery.getUserId());
    			ctx.writeAndFlush(userDO);
    		}
    	}
    
    	@Override
    	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    		
    		System.out.println("Server has Exception,"+ cause.getCause());
    	
    	}
    	
    	
    	private UserDO getUserById(int userId){
    		
    		if(userId % 2 == 0){
    			UserDO zhuoxuan = new UserDO();
    			zhuoxuan.setUserId(userId);
    			zhuoxuan.setSex(1);
    			zhuoxuan.setUname("卓轩");
    			zhuoxuan.setUnick("zhuoxuan");
    			zhuoxuan.setEmail("zhuoxuan@mogujie.com");
    			return zhuoxuan;
    		}else{
    			UserDO zhuoxuan = new UserDO();
    			zhuoxuan.setUserId(userId);
    			zhuoxuan.setSex(1);
    			zhuoxuan.setUname("张三");
    			zhuoxuan.setUnick("zhangsan");
    			zhuoxuan.setEmail("zhuoxuan@mogujie.com");
    			return zhuoxuan;
    		}	
    	}
    }</span><strong style="font-size: 14px;">
    </strong>

  4. ClientHander 代码

<span style="font-size:12px;">/**
 * 
 * <p>
 * 用户查询请求 Handler
 * </p>
 * 
 * @author 卓轩
 * @创建时间:2014年7月7日
 * @version: V1.0
 */
public class UserQueryClientHandler extends ChannelInboundHandlerAdapter {
	
	

	public UserQueryClientHandler() {
		
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		
		for (int i = 0; i < 100; i++) {
			UserQuery userQuery = new UserQuery();
			userQuery.setUserId(1001+i);
			ctx.write(userQuery);
		}
		ctx.flush();
		
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		
		String message = String.valueOf(msg);
		
		System.out.println("Netty-Client:Receive Message,"+ message);
	}
	
	

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

		System.out.println("Client has Exception,"+ cause.getCause());
	}
}</span>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值