netty基础教程-1、Helloworld(基于Http通信协议)

时间:2019-02-03作者:klpeng分类:IT综合浏览:12288评论:0

在学习netty之前,先来看看netty是什么;是怎么工作的

gradle依赖

dependencies {
    testCompile(
            "junit:junit:4.12"
    )
    // https://mvnrepository.com/artifact/io.netty/netty-all
    compile group: 'io.netty', name: 'netty-all', version: '4.1.32.Final'
}

服务端

处理的过程:

  1. 父事件组接受客户端的连接请求,
  2. 连接上后就交由子事件组进行处理(在处理请求时是有处理器来进行处理的)
  3. 创建父处理器,子处理器
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class TestServer {
    public static void main(String[] args) throws Exception {
        //创建两个事件处理组
        //父类用来处理客户端的连接操作,连接后交给客户端处理
        //子类处理客户端的请求
        EventLoopGroup parentGroup = new NioEventLoopGroup();
        EventLoopGroup childGroup = new NioEventLoopGroup();
        try {
            //创建服务启动类
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //为服务设置事件处理组、管道类型
            serverBootstrap.group(parentGroup, childGroup).channel(NioServerSocketChannel.class)
                    //设置子处理器
                    .childHandler(new TestServerInitialHandler());
            //启动
            ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
            channelFuture.channel().closeFuture().sync();
        }finally {
            parentGroup.shutdownGracefully();
            childGroup.shutdownGracefully();
        }
    }
}

处理器

TestServerInitialHandler

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 TestServerInitialHandler extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("httpCodec",new HttpServerCodec());
        pipeline.addLast("TestHttpServerHandler",new TestHttpServerHandler());
    }
}

TestHttpServerHandler

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        //设置返回的数据
        ByteBuf buffer = Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8);
        //创建返回的response对象
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,buffer);
        //设置消息头
        response.headers().set(HttpHeaderNames.CONTENT_TYPE,HttpHeaderValues.TEXT_PLAIN)
                .set(HttpHeaderNames.CONTENT_LENGTH,buffer.readableBytes());
        ctx.writeAndFlush(response);
    }
}

github源码: https://github.com/wcjwctwy/netty-study

打赏
文章版权声明:除非注明,否则均为彭超的博客原创文章,转载或复制请以超链接形式并注明出处。
相关推荐

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

猜你喜欢