学习netty我们也开始从hello world开始 这个demo很简单 这里就直接上代码了
package netty.Demo01;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class Server {
public static void main(String[] args) throws InterruptedException {
NioEventLoopGroup boss = new NioEventLoopGroup();
NioEventLoopGroup work = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(boss, work).channel(NioServerSocketChannel.class).childHandler(new PipInitlizer());
ChannelFuture future = bootstrap.bind(9011).sync();
future.channel().closeFuture().sync();
}finally {
boss.shutdownGracefully();
work.shutdownGracefully();
}
}
}
我们来看下 几大组件中 NioEventLoopGroup 主要是创建默认的线程,boss事件线程组主要用于接受客户端的请求事件,work线程组主要是处理对应的io事件
1:NioEventLoopGroup会对对应多个EventLoop
2:一个EventLoop只会对应一个chanel 因此一个channel只会分配一个线程去处理
3:一个chanel会对应一个ChannelPipeline 而一个ChannelPipeline会注册多个handler
下面我们来定义自己的管道
package netty.Demo01;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
public class PipInitlizer extends ChannelInitializer<SocketChannel> {
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline= ch.pipeline();
pipeline.addLast("解码器",new HttpServerCodec());
//下面就是自己的处理器
pipeline.addLast(new InitHandler());
}
}
管道对应的而处理器:
package netty.Demo01;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
public class InitHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf= Unpooled.copiedBuffer("hello world--------",CharsetUtil.UTF_8);
FullHttpResponse response= new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,buf);
response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH,buf.readableBytes());
ctx.writeAndFlush(response);
}
}
以上就是简单的hello world netty实现
我们再浏览器访问对应的请求地址http://127.0.0.1:9011/

本文详细介绍了使用Netty框架实现HelloWorld应用的过程,包括NioEventLoopGroup的作用,ServerBootstrap的配置,以及自定义管道处理器InitHandler的实现。通过本例,读者可以了解Netty的基本组件和工作原理。
621

被折叠的 条评论
为什么被折叠?



