写个简单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请求