netty002之代码初次相见

本文详细介绍使用Netty框架搭建简单HTTP服务器的过程,包括依赖配置、代码实现及测试方法。通过示例代码,读者可以了解如何创建服务器启动类、初始化管道、处理HTTP请求并返回响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

写个简单http服务器玩玩

一、依赖

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.42.Final</version>
</dependency>

二、代码

启动主类:

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 TestServer {

    public static void main(String[] args) throws InterruptedException {
        //bossGroup事件循环组:只获取连接即获取请求,但不处理,交给workerGroup处理
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {

            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
                    //子处理器
                    .childHandler(new TestServerInitializer());
            //为服务器绑定端口
            ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
            channelFuture.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
            //优雅的关闭
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();

        }

    }
}

 

public class TestServerInitializer  extends ChannelInitializer<SocketChannel> {
    /**
     *  初始化管道
     * @param socketChannel
     * @throws Exception
     */
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {

        ChannelPipeline pipeline = socketChannel.pipeline();
        //自定义handler名字,handler对象
        pipeline.addLast("httpServerCodec",new HttpServerCodec());
        pipeline.addLast("myTestHttpServerHandler",new TestHttpServerHandler());

    }
}

 

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.*;
import io.netty.util.CharsetUtil;

/**
 * http 响应
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    /**
     * 读取客户端请求,并给客户端响应的方法
     *
     * @param channelHandlerContext
     * @param httpObject
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
        if (httpObject instanceof HttpRequest) {
            // 响应内容
            String content2 = "Hello World!" + Thread.currentThread().getName() + "\r\n";
            ByteBuf content = Unpooled.copiedBuffer(content2, CharsetUtil.UTF_8);
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
            channelHandlerContext.writeAndFlush(response);

        }
    }
}

三、测试:利用curl命令模拟http请求

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值