Netty学习——入门篇3 基于传统I/O和Netty 简单实现Tomcat
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class NettyTomcat {
public static void main(String[] args) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
// 接收到消息时的处理逻辑
ByteBuf in = (ByteBuf) msg;
System.out.println("Received data: " + in.toString(io.netty.util.CharsetUtil.UTF_8));
}
});
}
});
// 启动服务器并绑定到指定的端口
ChannelFuture f = b.bind(8080).sync();
// 等待服务器关闭
f.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭事件循环组
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
这段代码使用Netty实现了一个简单的服务器,它监听8080端口,并将接收到的数据转换为字符串打印到控制台。这个例子展示了如何使用Netty快速地搭建一个网络应用程序的骨架,并且如何处理网络事件。
评论已关闭