Netty實現簡易http_server


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的實現。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM