netty之hello world

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

学习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/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值