Netty学习-java对象的序列化

package subscribeserver;

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;

public class SubscribeClient {
	
	public void connect(int port, String host) throws Exception {
		
		//客户端I/O读写的线程组
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			//辅助启动类
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class)
			.option(ChannelOption.TCP_NODELAY, true)
			.handler(new ChannelInitializer<SocketChannel>() {
				
				//内部类初始化Channel,设置handler
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(new ObjectDecoder(1024*1024, ClassResolvers.cacheDisabled((this.getClass().getClassLoader()))));
					ch.pipeline().addLast(new ObjectEncoder());
					ch.pipeline().addLast(new SubscribeClientHandler());
				}
				
			}); 
			
			ChannelFuture f = b.connect(host, port).sync();
			f.channel().closeFuture().sync();
		} finally {
			group.shutdownGracefully();
		}
	}
	
	public static void main(String[] args) throws Exception {
		int port = 8081;
		new SubscribeClient().connect(port, "127.0.0.1");
	}

}

package subscribeserver;

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

public class SubscribeClientHandler extends ChannelHandlerAdapter {
	
	
	
	public SubscribeClientHandler() {
		
	}
	
	//收到服务端的应答消息之后ChannelRead方法被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    	SubscribeResp resp = (SubscribeResp)msg;
    	System.out.println("receive server response ["+resp+"]");
    }
    
    private SubscribeReq req(int id) {
    	SubscribeReq req = new SubscribeReq();
    	req.setId(id);
    	req.setName("订单" + id);
    	return req;
    }
    
    //当客户端和服务端TCP链路建立成功之后, Netty的NIO线程会调用channelActive方法,发送消息给服务端
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    	for (int i = 0 ; i < 100; i++) {
            ctx.writeAndFlush(req(i));    		
    	}

    }

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

package subscribeserver;

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;

public class SubscribeServer {
	
	public void bind(int port) throws Exception {
		
		//NioEventLoopGroup 是个线程组,它包含了一组NIO线程组,专门用于网络事件的处理,实际上它们是Reactor线程组。
		//两个线程组一个用于服务端接收客户端的连接,另一个用于进行SocketChannel的网络读写
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		
		try {
			//启动NIO服务的辅助启动类
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
				.channel(NioServerSocketChannel.class)
				.option(ChannelOption.SO_BACKLOG, 1024)
				.childHandler(new ChildChannelHandler());
			
			//启动辅助类配置完成之后,调用bind方法绑定监听端口,调用sync同步阻塞方法等待绑定操作完成
			ChannelFuture f = b.bind(port).sync();
			
			//阻塞,等待服务端链路关闭之后main函数才退出
			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(1024*1024, ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
			arg0.pipeline().addLast(new ObjectEncoder());
			arg0.pipeline().addLast(new SubscribeServerHandler());
		}
		
	}
	
	
	public static void main(String[] args) throws Exception {
		int port = 8081;
//		if (args != null && args.length > 0) {
//			
//		}
		new SubscribeServer().bind(port);
	}
	
}

package subscribeserver;

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

public class SubscribeServerHandler extends ChannelHandlerAdapter {
	
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    	SubscribeReq req = (SubscribeReq)msg;
    	System.out.println("请求["+req+"]");
    	SubscribeResp resp = resp(req.getId());
    	ctx.write(resp);
	}
    
    private SubscribeResp resp(int id) {
    	SubscribeResp resp = new SubscribeResp();
    	resp.setId(id);
    	resp.setDesc("接收到id为" + id + "的订单");
    	return resp;
    }
	
	
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //flush将缓冲区中的消息全部写入到SocketChannel中
    	ctx.flush();
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //释放资源
    	cause.printStackTrace();
    	ctx.close();
    }
}

package subscribeserver;

import java.io.Serializable;

public class SubscribeReq implements Serializable {


	private static final long serialVersionUID = 1L;

	private int id;
	
	private String name;

	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;
	}

	@Override
	public String toString() {
		return "SubscribeReq [id=" + id + ", name=" + name + "]";
	}

	
}

package subscribeserver;

import java.io.Serializable;

public class SubscribeResp implements Serializable {

	private static final long serialVersionUID = 1L;
	
	
	private int id;
	
	private String desc;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}

	@Override
	public String toString() {
		return "SubscribeResp [id=" + id + ", desc=" + desc + "]";
	}
	
	
	
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值