netty学习三基于http协议服务端开发

直接上代码“”

server类

package com.montnets.customer.httpServer;

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;


public class server {
  

private static final int port = 6789; //设置服务端端口
    
    private static EventLoopGroup group = new NioEventLoopGroup();   // 通过nio方式来接收连接和处理连接
                
    private static ServerBootstrap sbt = new ServerBootstrap();

    public static void main(String[] args) throws InterruptedException {
        try {

            sbt.group(eventLoopGroup, eventLoopGroup1);
            sbt.channel(NioServerSocketChannel.class);
            sbt.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast("encoder", new HttpResponseEncoder());
                    socketChannel.pipeline().addLast("decoder", new HttpRequestDecoder());
                    socketChannel.pipeline().addLast("aggregator", new HttpObjectAggregator(10 * 1024 * 1024));
                    socketChannel.pipeline().addLast(new NettyServerHandler());
                }
            });
            // 服务器绑定端口监听
            ChannelFuture f = sbt.bind(port).sync();
            logger.info("企业微信消息推送接口线程启动成功");
            // 监听服务器关闭监听
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully(); 关闭EventLoopGroup,释放掉所有资源包括创建的线程
        }
    }
}
NettyServerHandler类
package com.montnets.customer.httpserver;

import com.montnets.customer.interfaces.ICqrbOpration;
import com.montnets.customer.model.CqrbBeanconfig;
import com.montnets.log.MontnetsLog;
import com.montnets.model.BeanFactory;
import com.montnets.model.Config;
import io.netty.buffer.ByteBuf;
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;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;


public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    private String result = "";
    String reqPath = "aa";



    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof FullHttpRequest)) {
            result = "未知请求!";
            send(ctx, result, HttpResponseStatus.BAD_REQUEST);
            return;
        }
        FullHttpRequest httpRequest = (FullHttpRequest) msg;
        try {
            //获取路径
            String path = httpRequest.getUri();
            //获取参数
            String body = getBody(httpRequest);
            //获取请求方法
            HttpMethod method = httpRequest.getMethod();
            //如果不是这个路径,就直接返回错误
            if (!reqPath.equalsIgnoreCase(path)) {
                result = "请求路径错误!";
                send(ctx, result, HttpResponseStatus.BAD_REQUEST);
                return;
            }
            //如果是GET请求
            if (HttpMethod.GET.equals(method)) {
                result = "请求类型错误";
                send(ctx, result, HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE);
                return;
            }
            //如果是POST请求
            if (HttpMethod.POST.equals(method)) {
                //接受到的消息,做业务逻辑处理...
                result = parsingAndDeal(body);
                send(ctx, result, HttpResponseStatus.OK);
                return;
            }

            //如果是PUT请求
            if (HttpMethod.PUT.equals(method)) {
                result = "请求类型错误";
                send(ctx, result, HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE);
                return;
            }
            //如果是DELETE请求
            if (HttpMethod.DELETE.equals(method)) {
                result = "请求类型错误";
                send(ctx, result, HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE);
                return;
            }
        } catch (Exception e) {
            LOGGER.error("处理请求异常"+e);
        } finally {
            //释放请求
            httpRequest.release();
        }
    }

 

    /**
     * 获取body参数
     *
     * @param request
     * @return
     */
    private String getBody(FullHttpRequest request) {
        ByteBuf buf = request.content();
        String bufString =  buf.toString(CharsetUtil.UTF_8);
        String decode = null;
        try {
            decode = URLDecoder.decode(bufString, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return  decode;
    }




    /**
     * 发送的返回值
     *
     * @param ctx     返回
     * @param context 消息
     * @param status  状态
     */
    private void send(ChannelHandlerContext ctx, String context, HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer(context, CharsetUtil.UTF_8));
        response.headers().set("Content-Type", "text/plain; charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

}

到这里服务端的大致框架已经搭建好,具体要做的业务可以在加上

简单的可以执行的demo例子可以查看一下博客:

https://www.cnblogs.com/crazylqy/p/4901820.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值