Netty - HTTP 服务

前言

1、TestServer.java

package com.guiguixia.netty.http;

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;

/**
 * @author wzcstart
 * @date 2021/6/26 - 21:09
 */
public class TestServer {


    public static void main(String[] args) throws Exception{
        EventLoopGroup bossGroup = bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = workerGroup = new NioEventLoopGroup(8);
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new TestServerInitializer());

            System.out.println("server is ok ...");

            ChannelFuture channelFuture = serverBootstrap.bind(8080).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

}

2、TestServerInitializer.java

package com.guiguixia.netty.http;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;

/**
 * @author wzcstart
 * @date 2021/6/26 - 21:10
 */
public class TestServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        //向管道添加处理器
        ChannelPipeline pipeline = ch.pipeline();
        //1、 添加netty自带的 编 - 解码处理器 HttpServerCodec
        pipeline.addLast("MyHttpServerCodec", new HttpServerCodec());
        //2、 添加自定义的处理器
        pipeline.addLast("MyTestHttpServerHandler", new TestHttpServerHandler());
    }
}

3、TestHttpServerHandler.java

package com.guiguixia.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * @author wzcstart
 * @date 2021/6/26 - 21:09
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    /*
    1、SimpleChannelInboundHandler 是 ChannelInboundHandlerAdapter的子类
    2、客户端和服务端之间互相通话封装的数据 HttpObject
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        System.out.println("pipeline hashcode="+ctx.channel().pipeline().hashCode()
                +", handler hashcode="+this.hashCode());
        System.out.println("msg 类型="+msg.getClass());
        System.out.println("客户端地址:"+ctx.channel().remoteAddress());

        //判断是否是http请求
        if (msg instanceof HttpRequest){

            HttpRequest httpRequest = (HttpRequest)msg;
            URI uri = new URI(httpRequest.uri());
            if ("/favicon.ico".equals(uri.getPath())){
                System.out.println("浏览器请求ico不做响应");
                return;
            }

            //构造内容
            ByteBuf context = Unpooled.copiedBuffer("hello,client我是龟龟", CharsetUtil.UTF_8);

            //设置 response
            FullHttpResponse response = new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK,
                    context);

            //构建 响应头
            HttpHeaders headers = response.headers();
            headers.set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=utf-8");
            headers.set(HttpHeaderNames.CONTENT_LENGTH,context.readableBytes());

            //将消息返回
            ctx.channel().writeAndFlush(response);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值