EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();

    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss, worker).channel(NioServerSocketChannel.class).childHandler(new InitHandler());
        ChannelFuture sync = bootstrap.bind(8080).sync();
        sync.channel().closeFuture().sync();
    }finally {
     boss.shutdownGracefully();
    }

InitHandler.java

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

HttpHandle.java

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

public class HttpHandle extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
        Channel channel = channelHandlerContext.channel();
        channel.remoteAddress();
        //System.out.println(httpObject.getClass());

        ByteBuf byteBuf= Unpooled.copiedBuffer("Nice", CharsetUtil.UTF_8);

        FullHttpResponse response=new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,byteBuf);

        response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH,byteBuf.readableBytes());

        channelHandlerContext.writeAndFlush(response);
    }
}


1814121891138138.jpg

Last modification:October 4th, 2018 at 09:48 am
如果觉得我的文章对你有用,请随意赞赏