码迷,mamicode.com
首页 > Web开发 > 详细

Netty4 之 简单搭建HTTP服务

时间:2015-06-29 20:39:46      阅读:330      评论:0      收藏:0      [点我收藏+]

标签:http   java   web   server   netty   

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
        
    }
}


Netty4 之 简单搭建HTTP服务

标签:http   java   web   server   netty   

原文地址:http://antlove.blog.51cto.com/10057557/1669114

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!