Netty4 之 简单搭建HTTP服务

server.HttpServer.java

package server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

import org.apache.log4j.Logger;

public class HttpServer {
	private Logger logger = Logger.getLogger(HttpServer.class);
    
    public void start(int port) throws Exception {
    	logger.info("Http Server listening on "+port+" ...");
    	
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
	                        // server端发送的是httpResponse,所以要使用HttpResponseEncoder进行编码
	                        ch.pipeline().addLast(new HttpResponseEncoder());
	                        // server端接收到的是httpRequest,所以要使用HttpRequestDecoder进行解码
	                        ch.pipeline().addLast(new HttpRequestDecoder());
	                        ch.pipeline().addLast(new HttpServerInboundHandler());
                    	}
                	}).option(ChannelOption.SO_BACKLOG, 128) 
             .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = b.bind(port).sync();

            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        HttpServer server = new HttpServer();
        server.start(8844);
    }
}

server.HttpServerInboundHandler.java

package server;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import java.util.Random;

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.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpRequest;

import org.apache.log4j.Logger;

public class HttpServerInboundHandler extends ChannelInboundHandlerAdapter{
	private Logger logger = Logger.getLogger(HttpServerInboundHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
    	
        if (msg instanceof HttpRequest) {
        	HttpRequest request = (HttpRequest) msg;

            String uri = request.getUri();
            logger.info("Uri:" + uri);
        }
        
        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;

            ByteBuf buf = content.content();
            System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8));
            buf.release();

            
            String res = "the random number from server is : "+new Random().nextInt(100);

            FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,OK, Unpooled.wrappedBuffer(res.getBytes("UTF-8")));
            response.headers().set(CONTENT_TYPE, "text/plain");
            response.headers().set(CONTENT_LENGTH,response.content().readableBytes());
            ctx.write(response);
            ctx.flush();
            ctx.close();
        }
        
        
        ctx.fireChannelRead(msg); // 跳转到下一个handler
        
    }
}

pom.xml

		<dependency>
			<groupId>io.netty</groupId>
			<artifactId>netty-all</artifactId>
			<version>4.0.29.Final</version>
		</dependency>


你可能感兴趣的:(Web,http,netty)