netty也可以作为一个小巧的http服务器使用。
1 package com.ming.netty.http.httpserver; 2 3 import java.net.InetSocketAddress; 4 5 import io.netty.bootstrap.ServerBootstrap; 6 import io.netty.channel.ChannelFuture; 7 import io.netty.channel.ChannelInitializer; 8 import io.netty.channel.nio.NioEventLoopGroup; 9 import io.netty.channel.socket.SocketChannel; 10 import io.netty.channel.socket.nio.NioServerSocketChannel; 11 import io.netty.handler.codec.http.HttpContentCompressor; 12 import io.netty.handler.codec.http.HttpObjectAggregator; 13 import io.netty.handler.codec.http.HttpRequestDecoder; 14 import io.netty.handler.codec.http.HttpResponseDecoder; 15 import io.netty.handler.stream.ChunkedWriteHandler; 16 17 public class HttpServer { 18 19 public static void main(String[] args) { 20 new HttpServer().run("127.0.0.1", 8500); 21 } 22 23 24 public void run(String addr,int port){ 25 NioEventLoopGroup boosGroup=new NioEventLoopGroup(); 26 NioEventLoopGroup workGroup=new NioEventLoopGroup(); 27 try { 28 ServerBootstrap bootstrap=new ServerBootstrap(); 29 bootstrap.group(boosGroup, workGroup); 30 bootstrap.channel(NioServerSocketChannel.class); 31 bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { 32 33 @Override 34 protected void initChannel(SocketChannel ch) throws Exception { 35 ch.pipeline().addLast("http-decoder",new HttpRequestDecoder()); 36 ch.pipeline().addLast("http-aggregator",new HttpObjectAggregator(65536));//定义缓冲数据量 37 ch.pipeline().addLast("encoder", new HttpResponseDecoder()); 38 ch.pipeline().addLast("chunkedWriter", new ChunkedWriteHandler()); 39 ch.pipeline().addLast("deflater", new HttpContentCompressor());//压缩作用 40 ch.pipeline().addLast("handler", new HttpServerHandler()); 41 } 42 43 }); 44 ChannelFuture f=bootstrap.bind(new InetSocketAddress(addr, port)).sync(); 45 System.out.println("启动服务器:"+f.channel().localAddress()); 46 //等等服务器端监听端口关闭 47 f.channel().closeFuture().sync(); 48 } catch (Exception e) { 49 e.printStackTrace(); 50 }finally{ 51 workGroup.shutdownGracefully(); 52 workGroup.shutdownGracefully(); 53 } 54 } 55 56 57 }
1 package com.ming.netty.http.httpserver; 2 3 import java.nio.ByteBuffer; 4 import java.util.Map; 5 6 import io.netty.buffer.ByteBuf; 7 import io.netty.buffer.Unpooled; 8 import io.netty.buffer.UnpooledByteBufAllocator; 9 import io.netty.channel.Channel; 10 import io.netty.channel.ChannelFutureListener; 11 import io.netty.channel.ChannelHandlerContext; 12 import io.netty.channel.SimpleChannelInboundHandler; 13 import io.netty.handler.codec.http.DefaultFullHttpRequest; 14 import io.netty.handler.codec.http.DefaultFullHttpResponse; 15 import io.netty.handler.codec.http.FullHttpResponse; 16 import io.netty.handler.codec.http.HttpContent; 17 import io.netty.handler.codec.http.HttpHeaders; 18 import io.netty.handler.codec.http.HttpMessage; 19 import io.netty.handler.codec.http.HttpRequest; 20 import io.netty.handler.codec.http.HttpResponseStatus; 21 import io.netty.handler.codec.http.HttpVersion; 22 import io.netty.handler.codec.http.LastHttpContent; 23 import io.netty.util.CharsetUtil; 24 25 public class HttpServerHandler extends SimpleChannelInboundHandler<Object> { 26 27 private HttpRequest request; 28 29 private ByteBuf buffer_body = UnpooledByteBufAllocator.DEFAULT.buffer(); 30 31 private StringBuffer sb_debug = new StringBuffer(); 32 33 @Override 34 protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception { 35 DefaultFullHttpRequest request=(DefaultFullHttpRequest)msg; 36 37 System.out.println("启动服务器:"+request.getMethod()+request.getUri()); 38 try { 39 if ((msg instanceof HttpMessage) && HttpHeaders.is100ContinueExpected((HttpMessage)msg)) { 40 ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE)); 41 } 42 if (msg instanceof HttpRequest) { 43 this.request = (HttpRequest)msg; 44 sb_debug.append("\n>> HTTP REQUEST -----------\n"); 45 sb_debug.append(this.request.getProtocolVersion().toString()) 46 .append(" ").append(this.request.getMethod().name()) 47 .append(" ").append(this.request.getUri()); 48 sb_debug.append("\n"); 49 HttpHeaders headers = this.request.headers(); 50 if (!headers.isEmpty()) { 51 for (Map.Entry<String, String> header : headers) { 52 sb_debug.append(header.getKey()).append(": ").append(header.getValue()).append("\n"); 53 } 54 } 55 sb_debug.append("\n"); 56 } else if (msg instanceof HttpContent) { 57 HttpContent content = (HttpContent) msg; 58 ByteBuf thisContent = content.content(); 59 if (thisContent.isReadable()) { 60 buffer_body.writeBytes(thisContent); 61 } 62 if (msg instanceof LastHttpContent) { 63 sb_debug.append(buffer_body.toString(CharsetUtil.UTF_8)); 64 LastHttpContent trailer = (LastHttpContent) msg; 65 if (!trailer.trailingHeaders().isEmpty()) { 66 for (String name : trailer.trailingHeaders().names()) { 67 sb_debug.append(name).append("="); 68 for (String value : trailer.trailingHeaders().getAll(name)) { 69 sb_debug.append(value).append(","); 70 } 71 sb_debug.append("\n\n"); 72 } 73 } 74 sb_debug.append("\n<< HTTP REQUEST -----------"); 75 } 76 } 77 } catch (Exception e) { 78 e.printStackTrace(); 79 } finally { 80 System.out.println(sb_debug+""); 81 FullHttpResponse response=new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.ACCEPTED); 82 String str="hello,my netty httpServer!"; 83 StringBuilder buf=new StringBuilder(); 84 buf.append("<!DOCTYPE html><head></head><body>").append(str).append("</body></html>"); 85 ByteBuf buffer=Unpooled.copiedBuffer(buf,CharsetUtil.UTF_8); 86 response.content().writeBytes(buffer); 87 response.headers().set("Content-Type", "text/html; charset=UTF-8"); 88 response.headers().set("Content-Length",1000); 89 buffer.release(); 90 ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); 91 92 93 } 94 } 95 96 97 98 99 100 101 102 }
时间: 2024-10-29 00:20:47