工作需要大致进行了学习,并不深入,只是简单的使用,若存在错误,欢迎大家指正,在后续系统学习后会更加深入的解释其中的配置。
一、netty模块配置
1.netty的依赖注入
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</dependency>
2、netty服务端配置
nettyServer配置
//创建成员变量主线程与工作线程
//一个主线程
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
//工作线程
NioEventLoopGroup workGroup = new NioEventLoopGroup(200);
//初始化服务配置(主要是对ServerBootstrap的配置),通过bind方法绑定监听ip端口的消息
InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8082);
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workGroup)
//指定channel
.channel(NioServerSocketChannel.class)
//使用指定的端口设置套接字地址
.localAddress(inetSocketAddress)
//指定日志级别
.handler(new LoggingHandler(LogLevel.INFO))
//设置服务端可连接队列数,对应TCP/IP协议listen函数中backlog参数
.option(ChannelOption.SO_BACKLOG, 1024)
//两小时没有数据通信时TCP会自动发送一个活动探测数据报文
.childOption(ChannelOption.SO_KEEPALIVE, true)
//添加自定义的初始化器
.childHandler(new ServerInitializer());
try {
ChannelFuture future = serverBootstrap.bind(inetSocketAddress).sync();
log.info("tcp服务开始监听端口:{}", inetSocketAddress.getPort());
if (future.isSuccess()) {
log.info("netty启动成功");
}
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
ServerInitializer配置
在nettyServer中serverBootstrap的配置中配置了.childHandler(new ServerInitializer()),该类需要继承ChannelInitializer<SocketChannel>,
并实现initChannel(SocketChannel socketChannel)方法,主要是用于指定编码器与解码器;
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
//String类的解码器
pipeline.addLast(new StringDecoder());
//String类的编码器
pipeline.addLast(new StringEncoder());
//配置server的处理器(对于消息的接收与处理等行为)
pipeline.addLast(new NettyServerHandler());
}
NettyServerHandler配置
在ServerInitializer中配置了 pipeline.addLast(new NettyServerHandler()),NettyServerHandler处理器需要继承SimpleChannelInboundHandler<XXXX>其中XXX为接收消息的对象类型,
并实现channelRead0(ChannelHandlerContext channelHandlerContext, XXXX xxx)方法(其中XXX为继承时的泛型类型),此处为打印netty接收到的消息。
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String str) throws Exception {
System.out.println(str);
}
3、netty客户端配置
nettyClient配置
客户端与服务端相似,不同的是服务端配置的ServerBootstrap客户端配置的是Bootstrap,bootstrap的connect方法指定连接到的ip与端口,消息会发往连接到的ip端口(使用bootstrap.connect()方法返回的对象的writeAndFlush方法写入对象发送)。
//配置线程组
NioEventLoopGroup group = new NioEventLoopGroup();
public void run(Object msg) {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
//指定channel
.channel(NioSocketChannel.class)
.handler(new ServerInitializer());
//连接
ChannelFuture connect;
try {
connect = bootstrap.connect("127.0.0.1", 8082).sync();
Channel channel = connect.channel();
log.info("连接netty成功");
channel.writeAndFlush(msg);
channel.closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
ClientInitializer配置
与serverInitializer相似,继承ChannelInitializer<SocketChannel>后实现initChannel(SocketChannel socketChannel)指定编码、解码器,并指定handler处理器。
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
//String类的解码器
pipeline.addLast(new StringDecoder());
//String类的编码器
pipeline.addLast(new StringEncoder());
pipeline.addLast(new NettyClientHandler());
}
NettyClientHandler配置
客户端的NettyClientHandler继承SimpleChannelInboundHandler<PersonOuterClass.Person>
实现channelRead0(ChannelHandlerContext channelHandlerContext, PersonOuterClass.Person person),根据业务需要实现该方法。其中的XXX为接收的参数类型。channelActive(ChannelHandlerContext ctx)在连接成功时会被触发。
@Slf4j
public class NettyClientHandler extends SimpleChannelInboundHandler<XXX> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, XXX xxx) throws Exception {
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("连接成功");
}
}
System.out.println("感谢阅读");