netty基本使用
基本api使用
服务端:
// 我们要创建两个EventLoopGroup,
// 一个是boss专门用来接收连接,可以理解为处理accept事件,
// 另一个是worker,可以关注除了accept之外的其它事件,处理子任务。
//上面注意,boss线程一般设置一个线程,设置多个也只会用到一个,而且多个目前没有应用场景
// worker线程通常要根据服务器调优,如果不写默认就是cpu的两倍。
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workGroup = new NioEventLoopGroup(4);
//服务端要启动,需要创建ServerBootStrap,
// 在这里面netty把nio的模板式的代码都给封装好了
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workGroup)
//指定 模型,server 的通道
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))// ServerSoccketChannel 对应的 handler
//具体的工作处理类,负责处理 相关的 SocketChannel 的 IO 就绪时间
//work 线程配置的 处理器
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline()
.addLast(new NormalMessageHandler());//自定义handler,处理 IO 请求
}
});
try {
//同步阻塞等到 客户端 请求连接
ChannelFuture channelFuture = bootstrap.bind(8080).sync();
System.out.println("Netty server started success:listener port 8080");
//同步 等打扫 服务端监听端口关闭
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
}finally {
workGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
注意: hander 和 chailhandler 的区别:
- handler 是 为 bossGroup 服务, 发生在初始化的时候
- childHandler 是为 workGroup 服务的, 发生在 客户端连接之后
客户端
//定义 EventLoopGroup
EventLoopGroup worker = new NioEventLoopGroup();
//客户端
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(worker).
//指定 客户端的通信通道
channel(NioSocketChannel.class)
// 定义 handler
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024*1024,
9,
4,
0,
0))
.addLast(new MessageRecordEncode())
.addLast(new MessageRecordDecode())
.addLast(new ClientHandler());
}
});
try {
ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 8080)).sync();
//模拟数据发送
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
worker.shutdownGracefully();
}

浙公网安备 33010602011771号