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

Netty实现简易http_server

时间:2018-10-16 20:21:45      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:exce   ...   plain   self   ora   div   buffer   img   lis   

Netty可以通过一些handler实现简单的http服务器。具体有三个类,分别是HttpServer.java、ServerHandlerInit.java、BusiHandler.java。

具体代码如下:

HttpServer.java

技术分享图片
package cn.enjoyedu.server;

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;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;

/**
 * @author Mark老师   享学课堂 https://enjoy.ke.qq.com
 * 往期课程和VIP课程咨询 依娜老师  QQ:2133576719
 * 类说明:
 */
public class HttpServer {
    public static final int port = 6789; //设置服务端端口
    private static EventLoopGroup group = new NioEventLoopGroup();
    private static ServerBootstrap b = new ServerBootstrap();
    private static final boolean SSL = true;

    public static void main(String[] args) throws Exception {
        final SslContext sslCtx;
        if (SSL) {
            //netty为我们提供的ssl加密,缺省
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(),
                    ssc.privateKey()).build();
        } else {
            sslCtx = null;
        }
        try {
            b.group(group);
            b.channel(NioServerSocketChannel.class);
            b.childHandler(new ServerHandlerInit(sslCtx));
            // 服务器绑定端口监听
            ChannelFuture f = b.bind(port).sync();
            System.out.println("服务端启动成功,端口是:"+port);
            // 监听服务器关闭监听
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}
View Code

ServerHandlerInit.java

技术分享图片
package cn.enjoyedu.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.ssl.SslContext;

/**
 * @author Mark老师   享学课堂 https://enjoy.ke.qq.com
 * 往期课程和VIP课程咨询 依娜老师  QQ:2133576719
 * 类说明:
 */
public class ServerHandlerInit extends ChannelInitializer<SocketChannel> {

    private final SslContext sslCtx;

    public ServerHandlerInit(SslContext sslCtx) {
        this.sslCtx = sslCtx;
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline ph = ch.pipeline();
        if (sslCtx != null) {
            ph.addLast(sslCtx.newHandler(ch.alloc()));
        }
        //http响应编码
        ph.addLast("encode",new HttpResponseEncoder());
        //http请求编码
        ph.addLast("decode",new HttpRequestDecoder());
        //聚合http请求
        ph.addLast("aggre",
                new HttpObjectAggregator(10*1024*1024));
        //启用http压缩
        ph.addLast("compressor",new HttpContentCompressor());
        //自己的业务处理
        ph.addLast("busi",new BusiHandler());

    }
}
View Code

BusiHandler.java

技术分享图片
package cn.enjoyedu.server;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * @author Mark老师   享学课堂 https://enjoy.ke.qq.com
 * 往期课程和VIP课程咨询 依娜老师  QQ:2133576719
 * 类说明:
 */
public class BusiHandler extends ChannelInboundHandlerAdapter {
    private String result="";

    private void send(String content, ChannelHandlerContext ctx,
                      HttpResponseStatus status){
        FullHttpResponse response =
                new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,status,
                        Unpooled.copiedBuffer(content,CharsetUtil.UTF_8));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE,
                "text/plain;charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);

    }

    /*
     * 收到消息时,返回信息
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        String result="";
        //接收到完成的http请求
        FullHttpRequest httpRequest = (FullHttpRequest)msg;

        try{
            String path = httpRequest.uri();
            String body = httpRequest.content().toString(CharsetUtil.UTF_8);
            HttpMethod method = httpRequest.method();
            if(!"/test".equalsIgnoreCase(path)){
                result = "非法请求:"+path;
                send(result,ctx,HttpResponseStatus.BAD_REQUEST);
                return;
            }

            //处理http GET请求
            if(HttpMethod.GET.equals(method)){
                System.out.println("body:"+body);
                result="Get request,Response="+RespConstant.getNews();
                send(result,ctx,HttpResponseStatus.OK);
            }

            //处理http POST请求
            if(HttpMethod.POST.equals(method)){
                //.....

            }

        }catch(Exception e){
            System.out.println("处理请求失败!");
            e.printStackTrace();
        }finally{
            httpRequest.release();
        }
    }

    /*
     * 建立连接时,返回消息
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx)
            throws Exception {
        System.out.println("连接的客户端地址:"
                + ctx.channel().remoteAddress());
    }
}
View Code

说明:

HttpServer.java就是实现一个http服务器,然后具体的handler入栈则是通过ServerHandlerInit.java实现。同时具体的http逻辑处理则是BusiHandler.java。

该示例实现了https的实现。

 

Netty实现简易http_server

标签:exce   ...   plain   self   ora   div   buffer   img   lis   

原文地址:https://www.cnblogs.com/duanjt/p/9800317.html

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