一、Netty是什麼
Netty是一個高性能、異步的NIO框架,基於Java NIO的特性進行封裝。它的出現,使得基於NIO的開發變得更加簡單,同時提高了性能和可靠性。在我們學習Netty之前,推薦閱讀以下兩本書籍:
二、《Netty權威指南》
《Netty權威指南》通俗易懂,適合入門學習。這本書旨在為使用Netty框架的開發人員提供一個全面的、深入的指南,涵蓋了網絡協議、異步編程和Netty API的所有方面。這本書分為七個部分,其中包括:Netty的架構和工作原理、Netty的基本組件和功能、網絡協議的實現、數據處理、安全性、優化和擴展。下面是一個簡單的Netty服務端的示例:
public class NettyServer {
public static void main(String[] args) throws InterruptedException {
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ChannelInitializer() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(new NettyServerHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(6668).sync();
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
class NettyServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println((String) msg);
ctx.writeAndFlush("服務端已接收到消息");
}
}
三、《深入分析Java Web技術內幕》
《深入分析Java Web技術內幕》是一本從Java基礎知識到實際應用場景的詳細闡述之書。在裡面,關於Netty的介紹並不是非常詳細,但是對於理解網絡原理和協議處理有着重要的幫助。如果你在使用Netty過程中,遇到了一些網絡協議的問題,這本書會給你提供新的思路。下面是一個簡單的HTTP服務端的示例:
public class HttpServer {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(1024 * 1024));
pipeline.addLast(new HttpServerHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
class HttpServerHandler extends SimpleChannelInboundHandler {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
System.out.println(msg.toString());
ByteBuf content = Unpooled.copiedBuffer("服務端已接收到消息", CharsetUtil.UTF_8);
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
ctx.writeAndFlush(response);
}
}
四、《Netty實戰》
《Netty實戰》是一個循序漸進的指南,適合開發人員逐步掌握Netty框架,並在實際應用中使用。該書覆蓋了Netty網絡編程的所有不同方面,包括:使用ByteBuf進行編解碼、使用ChannelHandler實現協議處理、使用EventLoop執行異步I/O操作以及使用Netty構建客戶端和服務端。下面是一個簡單的Netty客戶端的示例:
public class NettyClient {
public static void main(String[] args) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(new NettyClientHandler());
}
});
ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6668).sync();
channelFuture.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
}
class NettyClientHandler extends SimpleChannelInboundHandler {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush("客戶端發送消息");
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(msg);
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/185622.html
微信掃一掃
支付寶掃一掃