netty实现通信的步骤
1、创建两个NIO线程组,一个用于接受客户端连接,另一个处理网络读写。
2、创建一个ServerBootStrap,配置netty的一些列参数,例如接收传出数据的缓存大小等。
3、创建一个实际处理数据的类ChannelInitializer,进行初始化的准备工作,比如设置传出数据的字符集、格式、已经实际处理数据的接口。
4、绑定端口,执行同步阻塞方法等待服务器端启动即可。
//服务端启动助手
public static void startServer(String ip, int port) throws InterruptedException {
//1.创建两个线程池对象
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
NioEventLoopGroup workGroup = new NioEventLoopGroup();
//2.创建服务端的启动引导对象
ServerBootstrap serverBootstrap = new ServerBootstrap();
//3.配置启动引导对象
serverBootstrap.group(bossGroup, workGroup)
//设置通道为NIO
.channel(NioServerSocketChannel.class)
//创建监听channel
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
//获取管道对象
ChannelPipeline pipeline = nioSocketChannel.pipeline();
//给管道对象pipeLine 设置编码
pipeline.addLast(new StringEncoder());
pipeline.addLast(new StringDecoder());
// pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
//把我们自顶一个ChannelHander添加到通道中
pipeline.addLast(new UserServiceHandler());
}
});
//4.绑定端口
serverBootstrap.bind(8999).sync();
}
//客户端启动助手
public static void initClient() throws InterruptedException {
//1) 初始化UserClientHandler
userClientHandler = new UserClientHandler();
//2)创建连接池对象
EventLoopGroup group = new NioEventLoopGroup();
//3)创建客户端的引导对象
Bootstrap bootstrap = new Bootstrap();
//4)配置启动引导对象
bootstrap.group(group)
//设置通道为NIO
.channel(NioSocketChannel.class)
//设置请求协议为TCP
.option(ChannelOption.TCP_NODELAY,true)
//监听channel 并初始化
.handler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel socketChannel) throws Exception {
//获取ChannelPipeline
ChannelPipeline pipeline = socketChannel.pipeline();
//设置编码
pipeline.addLast(new StringEncoder());
//pipeline.addLast(new RpcEncoder(RpcRequest.class,new JSONSerializer()));
pipeline.addLast(new StringDecoder());
//添加自定义事件处理器
pipeline.addLast(userClientHandler);
}
});
//5)连接服务端
bootstrap.connect("127.0.0.1",8999).sync();
}