使用netty4创建http服务,代码如下:
NettyHttpServer:
import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponseEncoder; public class NettyHttpServer { private static final int port = 9090; private void bind(int port) throws Exception{ EventLoopGroup group = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(group) .channel(NioServerSocketChannel.class) .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(65536)); socketChannel.pipeline().addLast("handler", new NettyHttpServerHandler()); } }); ChannelFuture f = b.bind(port).sync(); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } public static void main(String[] args)throws Exception { new NettyHttpServer().bind(port); } }
NettyHttpServerHandler:
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; public class NettyHttpServerHandler extends ChannelInboundHandlerAdapter{ private final String url = "/hello"; @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("客户端连接成功"); super.channelActive(ctx); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { String result; if (!(msg instanceof FullHttpRequest)) { result = "错误请求"; this.send(ctx, result, HttpResponseStatus.BAD_REQUEST); return; } FullHttpRequest httpRequest = (FullHttpRequest)msg; try { String path = httpRequest.uri(); HttpMethod method = httpRequest.method(); if (!url.equals(path)) { result = "请求路径错误"; this.send(ctx, result, HttpResponseStatus.BAD_REQUEST); return; } if (!HttpMethod.GET.equals(method)) { result = "请求方法错误"; this.send(ctx, result, HttpResponseStatus.METHOD_NOT_ALLOWED); return; } result = "Welcome to netty http server"; this.send(ctx, result, HttpResponseStatus.OK); } finally { httpRequest.release(); } } 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(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } }
这样一个简单的Netty的http服务便写好了。
打开浏览器测试如下: