Netty二(Http服务器)

本文介绍如何使用Netty高性能IO工具包开发HTTP服务器,通过示例代码详细展示了服务器的搭建过程,包括EventLoopGroup的创建、ServerBootstrap的配置、管道处理器的添加以及请求处理等关键步骤。

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

Netty—Http服务器

一.简介

Netty一个高性能IO工具包,主要用于开发HTTP服务器,HTTPS服务器,WebSocket服务器,TCP服务器,UDP服务器和在JVM管道。用Netty开发的服务器可单独运行(即:在main()函数里调用),不需要部署在类似tomcat的容器里。Netty使用单线程并发模型,并围绕非阻塞NIO设计,所以性能较高。

二.http服务器示例

public class NerryHttpServer {
	public static void main(String[] args) {
		EventLoopGroup group = new NioEventLoopGroup();
		ServerBootstrap bootstrap = new ServerBootstrap();

		bootstrap.group(group);
		bootstrap.channel(NioServerSocketChannel.class);

		bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
			@Override
			protected void initChannel(SocketChannel socketChannel) throws Exception {
				socketChannel.pipeline().addLast("http-decoder", new HttpRequestDecoder());
				socketChannel.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65535));// 将多个消息转化成一个
				socketChannel.pipeline().addLast("http-encoder", new HttpResponseEncoder());
				socketChannel.pipeline().addLast("http-chunked", new ChunkedWriteHandler());// 解决大码流的问题
				socketChannel.pipeline().addLast(new NettyServerHandler());
			}
		});

		try {
			ChannelFuture channelFuture = bootstrap.bind(8899).sync();
			channelFuture.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			group.shutdownGracefully();
		}
	}
}

class NettyServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
		try {			
			String requestMethod = "";
			if (msg.getMethod() == HttpMethod.GET) {
				requestMethod = "the request method is GET";
			} else if (msg.getMethod() == HttpMethod.POST) {
				requestMethod = "the request method is POST";
			}
			FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
		
			ByteBuf responseBuf = Unpooled.copiedBuffer(requestMethod, CharsetUtil.UTF_8);
			response.content().writeBytes(responseBuf);
			responseBuf.release();
			ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值