Netty入門(一):零基礎“HelloWorld”詳細步驟

來來來寫一個Netty “hello world”。

首先看一下API

netty 官方API: http://netty.io/4.1/api/index.html

一、添加maven依賴

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>5.0.0.Alpha2</version>
</dependency>

二、創建服務端

package netty;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;


public class HttpServer {


    private final int port;


    public HttpServer(int port) {
        this.port = port;
    }


    public static void main(String[] args){
        int port = 20008;
        try {
            new HttpServer(port).start();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    public void start() throws Exception {
        ServerBootstrap b = new ServerBootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        b.group(group)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch){
                        System.out.println("======initChannel ch:" + ch);
                        //  基於HTTP協議的。需要注意這邊設置的要和handler端的類型一樣
//                        ch.pipeline()
//                                .addLast("decoder", new HttpRequestDecoder())   // 1
//                                .addLast("encoder", new HttpResponseEncoder())  // 2
////                                .addLast("aggregator", new HttpObjectAggregator(512 * 1024))    // 3
//                                .addLast("aggregator", new HttpObjectAggregator(65536))
//                                .addLast("http-codec", new HttpServerCodec())
//                                .addLast(new HttpHandler());        // 4
                        // 無限制默認
                        ch.pipeline().addLast(new HttpHandler());


                    }


                })
                .option(ChannelOption.SO_BACKLOG, 128) // determining the number of connections queued
                .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);


        b.bind(port).sync();
    }
}


三、創建handler

package netty;


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.AsciiString;


public class HttpHandler extends SimpleChannelInboundHandler<Object> { // 1


    private AsciiString contentType = HttpHeaderValues.TEXT_PLAIN;


   // 接受數據
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
        System.out.println("class:" + msg.getClass().getName());
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                Unpooled.wrappedBuffer("test".getBytes())); // 2


        HttpHeaders heads = response.headers();
        heads.add(HttpHeaderNames.CONTENT_TYPE, contentType + "; charset=UTF-8");
        heads.add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); // 3
        heads.add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);


        ctx.write(response);
    }
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelReadComplete");
        super.channelReadComplete(ctx);
        ctx.flush(); // 4
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("exceptionCaught");
        if (null != cause) cause.printStackTrace();
        if (null != ctx) ctx.close();
    }


}

三、運行服務端,然後ping一下對應的接口,觀察控制檯打印。

一個netty hello world就OK了。

發佈了144 篇原創文章 · 獲贊 38 · 訪問量 26萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章