如果你是做java开发的boy,netty是一个绕不开的网络框架,它在多个流行的开源系统中被广泛使用,比如dubbo、es、spring、rocketmq等等;如果你要自己实现一个基于TCP的网络服务,使用netty框架会让我们只需要关注业务代码开发而不用更多的关心底层处理逻辑,下面就用一个简单的示例代码展示如何使用netty实现一个C/S架构。
代码逻辑非常简单:客户端向服务端发送一个字符串,服务端接收到字符串同时向客户端返回响应。
首先需要引入相关的依赖包,线上netty分为netty4和netty5两个分支,由于netty5代码复杂但是性能并没有得到很大的提升,所以不推荐使用:
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.90.Final</version>
</dependency>
netty代码基本属于模板式开发,对于业务人员来说,只需要按照代码规范在调用链中添加相关的handler,而用户的业务处理逻辑也都是写在handler中。
服务端代码基本如下:
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @Author xingo
* @Date 2023/10/11
*/
public class NettyServer implements Runnable {
/**
* 服务端IP地址
*/
private String ip;
/**
* 服务端端口号
*/
private int port;
public NettyServer(String ip, int port) {
this.ip = ip;
this.port = port;
}
@Override
public void run() {
// 指定boss线程数:主要负责接收连接请求,一般设置为1就可以
final EventLoopGroup boss = new NioEventLoopGroup(1, new ThreadFactory() {
private AtomicInteger index = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, String.format("NioBoss_%d", this.index.incrementAndGet()));
}
});
// 指定worker线程数:主要负责处理连接就绪的连接,一般设置为CPU的核心数
final int totalThread = 12;
final EventLoopGroup worker = new NioEventLoopGroup(totalThread, new ThreadFactory() {
private AtomicInteger index = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, String.format("NioSelector_%d_%d", totalThread, this.index.incrementAndGet()));
}
});
// 指定任务处理线程数:主要负责读取数据和处理响应,一般该值设置的比较大,与业务相对应
final int jobThreads = 1024;
final EventLoopGroup job = new DefaultEventLoopGroup(jobThreads, new ThreadFactory() {
private AtomicInteger index = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, String.format("NioJob_%d_%d", jobThreads, this.index.incrementAndGet()));
}
});
// 日志处理handler:类定义上面有Sharable表示线程安全,可以将对象定义在外面使用
final LoggingHandler LOGGING_HANDLER = new LoggingHandler();
// 指定服务端bootstrap
ServerBootstrap server = new ServerBootstrap();
server.group(boss, worker)
// 指定通道类型
.channel(NioServerSocketChannel.class)
// 指定全连接队列大小:windows下默认是200,linux/mac下默认是128
.option(ChannelOption.SO_BACKLOG, 2048)
// 维持链接的活跃,清除死链接
.childOption(ChannelOption.SO_KEEPALIVE, true)
// 关闭延迟发送
.childOption(ChannelOption.TCP_NODELAY, true)
// 添加handler处理链
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
// 日志处理
pipeline.addLast(LOGGING_HANDLER);
// 心跳检测:读超时时间、写超时时间、全部超时时间(单位是秒,0表示不处理)
pipeline.addLast(new IdleStateHandler(30,0,0, TimeUnit.SECONDS));
pipeline.addLast(new ChannelDuplexHandler() {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
IdleStateEvent event = (IdleStateEvent) evt;
System.out.println("心跳事件 : " + event.state());
super.userEventTriggered(ctx, evt);
}
});
// 处理http请求的编解码器
// pipeline.addLast(job, "serverCodec", new HttpServerCodec());
// pipeline.addLast(job, "writeHandler", new ChunkedWriteHandler());
// pipeline.addLast(job, "httpHandler", new HttpObjectAggregator(64 * 1024));
// 处理websocket的编解码器
// pipeline.addLast(job, "websocketHandler", new WebSocketServerProtocolHandler("/ws", "WebSocket", true, 65536 * 10));
// 由于消息是字符串类型,所以这里添加字符串相关的编码器和解码器
pipeline.addLast(job, "stringEncoder", new StringEncoder());
pipeline.addLast(job, "stringDecoder", new StringDecoder());
// 自定义处理器
pipeline.addLast(job, "userHandler", new UserServerHandler());
}
});
try {
// 服务端绑定对外服务地址
ChannelFuture future = server.bind(ip, port).sync();
System.out.println("netty server start ok.");
// 等待服务关闭,关闭后释放相关资源
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
job.shutdownGracefully();
}
}
}
这里代码的编写基本是模板式的,用户只需要定义好自己需要处理的handler类,并把自己定义的handler加入到pipeline中就可以了,剩下的就是开发handler中的业务逻辑了,比如这里我指定了一个UserServerHandler类:服务端接收到消息,并向客户端返回信息。
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
* @Author xingo
* @Date 2023/10/11
*/
public class UserServerHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(msg);
ctx.writeAndFlush("server receive message : " + msg);
}
}
对于客户端开发也跟服务端基本一致:
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import java.util.concurrent.TimeUnit;
/**
* @Author xingo
* @Date 2023/10/11
*/
public class NettyClient implements Runnable {
/**
* 服务端IP地址
*/
private String ip;
/**
* 服务端端口号
*/
private int port;
/**
* 客户端写通道
*/
private Channel channel;
public NettyClient(String ip, int port) {
this.ip = ip;
this.port = port;
}
public Channel getChannel() {
return channel;
}
@Override
public void run() {
// 日志处理handler:类定义上面有Sharable表示线程安全
final LoggingHandler LOGGING_HANDLER = new LoggingHandler();
// 工作线程组
final NioEventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
ChannelFuture client = bootstrap.group(group)
.channel(NioSocketChannel.class)
// 指定连接超时时间
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
// 添加handler处理链
.handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
// 日志处理
pipeline.addLast(LOGGING_HANDLER);
// 心跳检测:读超时时间、写超时时间、全部超时时间(单位是秒,0表示不处理)
pipeline.addLast(new IdleStateHandler(0, 25, 0, TimeUnit.SECONDS));
pipeline.addLast(new ChannelDuplexHandler() {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
IdleStateEvent event = (IdleStateEvent) evt;
System.out.println("心跳事件 : " + event.state());
super.userEventTriggered(ctx, evt);
}
});
// 由于消息是字符串类型,所以这里添加字符串相关的编码器和解码器
pipeline.addLast(group, "stringEncoder", new StringEncoder());
pipeline.addLast(group, "stringDecoder", new StringDecoder());
// 添加自定义handler
pipeline.addLast(group, "clientHandler", new UserClientHandler());
}
}).connect(ip, port);
try {
// 阻塞等待客户端连接
client.sync();
// 客户端通道
Channel channel = client.channel();
this.channel = channel;
// 监听通道关闭future
ChannelFuture closeFuture = channel.closeFuture();
closeFuture.addListener((ChannelFutureListener) channelFuture -> {
System.out.println("客户端关闭处理相关操作!");
group.shutdownGracefully();
});
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
添加客户端的业务处理UserClientHandler:
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
* @Author xingo
* @Date 2023/10/11
*/
public class UserClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(msg);
}
}
下面定义一个测试类用于启动服务端:
/**
* @Author xingo
* @Date 2023/10/11
*/
public class ServerTest {
/**
* 服务器对外服务IP
*/
public static final String SERVER_IP = "127.0.0.1";
/**
* 服务器对外端口号
*/
public static final int SERVER_PORT = 8888;
public static void main(String[] args) {
new Thread(new NettyServer(SERVER_IP, SERVER_PORT)).start();
}
}
再定义一个测试类用于启动客户端:
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
/**
* @Author xingo
* @Date 2023/10/11
*/
public class ClientTest {
public static void main(String[] args) {
NettyClient nettyClient = new NettyClient(ServerTest.SERVER_IP, ServerTest.SERVER_PORT);
new Thread(nettyClient).start();
while (nettyClient.getChannel() == null) {
try {
TimeUnit.MICROSECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
while (true) {
if("##$$".equals(line)) {
nettyClient.getChannel().close();
break;
}
if(line != null && !line.trim().equals("")) {
nettyClient.getChannel().writeAndFlush(line);
}
line = scanner.nextLine();
}
}
}
客户端启动后,会在命令行等待用户输入信息,如果输入的内容是 ##$$ 那么客户端将关闭连接推出服务,其他的非空内容客户端都会将输入数据发送给服务端。
至此,一个简单的netty示例程序就开发完成了,netty确实是一个非常优秀的网络开发框架,它简化了代码的开发逻辑,并且社区也非常活跃,对于想要实现TCP业务的小伙伴它确实是第一选择。
由于他底层是基于NIO的Reactor模式使得性能非常高效,并且也解决了原生socket编程中的bug(在同步非阻塞epoll模式下的空轮询导致CPU飙升);并且netty中的Channel是线程安全的,在编程中不用考虑线程安全问题;在netty中重新定义了ByteBuf,解决了原生ByteBuffer使用中的不方便问题;对于半包和粘包问题netty中也给出了很好的解决方案,并且提供了大量的编解码器进一步简化开发工作。总之,netty对于开发者来说非常简单并且易用,如果入门来说,上面的代码已经足够了,但要更深入的了解它的工作原理以及底层逻辑,还是要深入源码阅读才行。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/181854.html