`

Netty4.0学习笔记系列之三:构建简单的http服务

阅读更多

        本文主要介绍如何通过Netty构建一个简单的http服务。

        想要实现的目的是:

        1.Client向Server发送http请求。

        2.Server端对http请求进行解析。

        3.Server端向client发送http响应。

        4.Client对http响应进行解析。

        在该实例中,会涉及到http请求的编码、解码,http响应的编码、解码,幸运的是,Netty已经为我们提供了这些工具,整个实例的逻辑图如下所示:


        其中红色框中的4个类是Netty提供的,它们其实也是一种Handler,其中Encoder继承自ChannelOutboundHandler,Decoder继承自ChannelInboundHandler,它们的作用是:

        1.HttpRequestEncoder:对httpRequest进行编码。

        2.HttpRequestDecoder:把流数据解析为httpRequest。

        3.HttpResponsetEncoder:对httpResponset进行编码。

        4.HttpResponseEncoder:把流数据解析为httpResponse。

        该实例涉及到的类有5个:HttpServer.java、HttpServerInboundHandler.java、HttpClient.java、HttpClientInboundHandler.java、ByteBufToBytes.java

1.HttpServer启动http服务器

package com.bijian.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
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.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

public class HttpServer {

    public void start(int port) throws Exception {

        EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap(); // (2)
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3)
                    .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                                @Override
                                public void initChannel(SocketChannel ch) throws Exception {
                                    // server端发送的是httpResponse,所以要使用HttpResponseEncoder进行编码
                                    ch.pipeline().addLast(new HttpResponseEncoder());
                                    // server端接收到的是httpRequest,所以要使用HttpRequestDecoder进行解码
                                    ch.pipeline().addLast(new HttpRequestDecoder());
                                    ch.pipeline().addLast(new HttpServerInboundHandler());
                                }
                            }).option(ChannelOption.SO_BACKLOG, 128) // (5)
                    .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

            ChannelFuture f = b.bind(port).sync(); // (7)

            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        HttpServer server = new HttpServer();
        server.start(8000);
    }
}

2.HttpServerInboundHandler解析客户端的请求,并进行响应

package com.bijian.netty.server;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpHeaders.Values;
import io.netty.handler.codec.http.HttpRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bijian.netty.util.ByteBufToBytes;

public class HttpServerInboundHandler extends ChannelInboundHandlerAdapter {
    
    private static Logger logger = LoggerFactory.getLogger(HttpServerInboundHandler.class);
    private ByteBufToBytes reader;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof HttpRequest) {
            HttpRequest request = (HttpRequest) msg;
            System.out.println("messageType:" + request.headers().get("messageType"));
            System.out.println("businessType:" + request.headers().get("businessType"));
            if (HttpHeaders.isContentLengthSet(request)) {
                reader = new ByteBufToBytes((int) HttpHeaders.getContentLength(request));
            }
        }

        if (msg instanceof HttpContent) {
            HttpContent httpContent = (HttpContent) msg;
            ByteBuf content = httpContent.content();
            reader.reading(content);
            content.release();

            if (reader.isEnd()) {
                String resultStr = new String(reader.readFull());
                System.out.println("Client said:" + resultStr);

                FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer("I am ok"
                        .getBytes()));
                response.headers().set(CONTENT_TYPE, "text/plain");
                response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
                response.headers().set(CONNECTION, Values.KEEP_ALIVE);
                ctx.write(response);
                ctx.flush();
            }
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        logger.info("HttpServerInboundHandler.channelReadComplete");
        ctx.flush();
    }
}

3.HttpClient 向服务器发送请求

package com.bijian.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.handler.codec.http.HttpVersion;

import java.net.URI;

public class HttpClient {
    
    public void connect(String host, int port) throws Exception {
        
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        
        try {
            Bootstrap b = new Bootstrap(); // (1)
            b.group(workerGroup); // (2)
            b.channel(NioSocketChannel.class); // (3)
            b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
                    ch.pipeline().addLast(new HttpResponseDecoder());
                    // 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
                    ch.pipeline().addLast(new HttpRequestEncoder());
                    ch.pipeline().addLast(new HttpClientInboundHandler());
                }
            });

            // Start the client.
            ChannelFuture f = b.connect(host, port).sync(); // (5)

            URI uri = new URI("http://127.0.0.1:8000");
            String msg = "Are you ok?";
            DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
                    uri.toASCIIString(), Unpooled.wrappedBuffer(msg.getBytes()));

            // 构建http请求
            request.headers().set(HttpHeaders.Names.HOST, host);
            request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
            request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
            request.headers().set("messageType", "normal");
            request.headers().set("businessType", "testServerState");
            // 发送http请求
            f.channel().write(request);
            f.channel().flush();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        HttpClient client = new HttpClient();
        client.connect("127.0.0.1", 8000);
    }
}

4.HttpClientInboundHandler 对服务器的响应进行读取

package com.bijian.netty.client;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponse;

import com.bijian.netty.util.ByteBufToBytes;

public class HttpClientInboundHandler extends ChannelInboundHandlerAdapter {
    
    private ByteBufToBytes reader;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        
        if (msg instanceof HttpResponse) {
            HttpResponse response = (HttpResponse) msg;
            System.out.println("CONTENT_TYPE:" + response.headers().get(HttpHeaders.Names.CONTENT_TYPE));
            if (HttpHeaders.isContentLengthSet(response)) {
                reader = new ByteBufToBytes((int) HttpHeaders.getContentLength(response));
            }
        }

        if (msg instanceof HttpContent) {
            HttpContent httpContent = (HttpContent) msg;
            ByteBuf content = httpContent.content();
            reader.reading(content);
            content.release();

            if (reader.isEnd()) {
                String resultStr = new String(reader.readFull());
                System.out.println("Server said:" + resultStr);

                ctx.close();
            }
        }
    }
}

5.ByteBufToBytes 读取NIO的工具类,可以一次性把ByteBuf的数据读取出来,也可以把多次ByteBuf中的数据统一读取出来。

package com.bijian.netty.util;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

public class ByteBufToBytes {
    
    private ByteBuf temp;

    private boolean end = true;

    public ByteBufToBytes(int length) {
        temp = Unpooled.buffer(length);
    }

    public void reading(ByteBuf datas) {
        datas.readBytes(temp, datas.readableBytes());
        if (this.temp.writableBytes() != 0) {
            end = false;
        } else {
            end = true;
        }
    }

    public boolean isEnd() {
        return end;
    }

    public byte[] readFull() {
        if (end) {
            byte[] contentByte = new byte[this.temp.readableBytes()];
            this.temp.readBytes(contentByte);
            this.temp.release();
            return contentByte;
        } else {
            return null;
        }
    }

    public byte[] read(ByteBuf datas) {
        byte[] bytes = new byte[datas.readableBytes()];
        datas.readBytes(bytes);
        return bytes;
    }
}

注意事项:

        1.可以通过在Netty的Chanel中发送HttpRequest对象,完成发送http请求的要求,同时可以对HttpHeader进行设置。

        2.可以通过HttpResponse发送http响应,同时可以对HttpHeader进行设置。

        3.上面涉及到的http对象都是Netty自己封装的,不是标准的。

 

文章来源:http://blog.csdn.net/u013252773/article/details/21254257

  • 大小: 36.4 KB
分享到:
评论

相关推荐

    Netty4.0学习笔记系列之四:混合使用coder和handler

    在本篇Netty4.0学习笔记中,我们将聚焦于如何在实际应用中混合使用`coder`和`handler`,这是Netty框架中非常关键的一部分,对于构建高性能、低延迟的网络应用程序至关重要。Netty是一个用Java编写的异步事件驱动的...

    Netty4.0学习笔记系列之五:自定义通讯协议

    在本篇“Netty4.0学习笔记系列之五:自定义通讯协议”中,我们将深入探讨如何在Netty框架下构建和实现自己的通信协议。Netty是一个高性能、异步事件驱动的网络应用框架,广泛应用于Java领域的服务器开发,如网络游戏...

    Netty4.0学习笔记系列之二:Handler的执行顺序

    在本篇“Netty4.0学习笔记系列之二:Handler的执行顺序”中,我们将深入探讨Netty中的Handler处理链以及它们的执行流程。 首先,Netty 中的 ChannelHandler 是处理 I/O 事件或拦截 I/O 操作的核心组件。每个 ...

    Netty4.0学习笔记系列之六:多种通讯协议支持

    在本篇Netty4.0学习笔记系列之六中,我们将深入探讨Netty框架如何支持多种通讯协议,以及它在实现高效、灵活的网络通信中的关键特性。Netty是一个高性能、异步事件驱动的网络应用框架,适用于开发服务器和客户端的...

    Netty4.0学习笔记系列之一:Server与Client的通讯

    在本文中,我们将深入探讨Netty 4.0的学习笔记,特别是关于Server与Client之间的通信机制。 首先,我们要理解Netty的核心概念——NIO(非阻塞I/O)。Netty基于Java NIO库构建,它提供了更高级别的API,简化了多路...

    Netty4.0 http案例

    在这个“Netty4.0 http案例”中,我们将深入探讨如何利用Netty 4.0 实现HTTP服务,以及客户端如何通过HTTP请求与服务器进行交互,特别是在处理JSON格式的数据时。 首先,让我们了解HTTP协议。HTTP(超文本传输协议...

    Netty4.0 jar包 及 源代码 和 例子

    Netty4.0全部jar包.开发时候只需要倒入总的哪一个netty4.0.jar就行了 后缀为resources.jar的全部是源码。 简单的代码例子在netty-example-resources.jar里面。

    Netty4.0 官网例子(免费)

    通过 Netty 的官网例子,你可以深入学习这些概念并了解如何在实际项目中运用。官方示例通常覆盖了基础到高级的各种用法,是理解和掌握 Netty4.0 的良好起点。你可以从 netty-4.0 压缩包中的源代码开始,逐步分析和...

    netty4.0文件分片上传+断点续传+权限校验

    Netty 是一个高性能、异步事件驱动的网络应用程序框架,常用于开发高并发、低延迟的网络服务,如TCP、UDP、HTTP等协议的应用。在本文中,我们将深入探讨如何利用Netty 4.0实现文件分片上传、断点续传以及权限校验的...

    netty4.0.45jar包socket和http工具包

    Netty的Socket支持使得开发者能够构建可靠的TCP和UDP服务。在Netty中,Socket编程被抽象为Channel接口,它允许你读取、写入数据,并处理连接、断开等事件。Netty 4.0.45提供了高度优化的NIO(非阻塞I/O)和EPOLL...

    netty4.0工具包

    NIO socket开发,netty4.0工具包。

    Springboot 2.0 整合 Netty 4.0 实现IO异步通讯架构

    Springboot2.0.8集成 netty4 ,使用protobuf作为ping的数据交换,比json更加的小巧,占用数据量更小,可用于任何第三方应用做心跳监控。 已完成功能: - 客户端授权验证(基于protoBuff) - 心跳检测(基于protoBuff) ...

    netty-all-4.0.50.Final-API文档-中文版.zip

    赠送jar包:netty-all-4.0.50.Final.jar; 赠送原API文档:netty-all-4.0.50.Final-javadoc.jar; 赠送源代码:netty-all-4.0.50.Final-sources.jar; 赠送Maven依赖信息文件:netty-all-4.0.50.Final.pom; 包含...

    netty4.0源码,netty例子,netty api文档

    这个压缩包包含的是Netty 4.0.0.CR3版本的相关资源,包括源码、示例以及API文档,对于学习和理解Netty的工作原理以及如何在实际项目中应用Netty非常有帮助。 首先,让我们来详细探讨一下Netty的核心特性: 1. **...

    netty4.0 demo

    通过对"Netty4.0 demo"的学习,我们可以掌握Netty的基本用法,理解其异步事件驱动模型,以及如何构建和配置处理器链来处理网络通信。这些示例代码对于初学者来说是很好的实践材料,有助于快速上手Netty并应用于实际...

    Netty (netty-netty-4.0.56.Final.tar.gz)

    Netty (netty-netty-4.0.56.Final.tar.gz)是一个 NIO 客户端服务器框架,可以快速轻松地开发协议服务器和客户端等网络应用程序。它极大地简化和流线了网络编程,例如 TCP 和 UDP 套接字服务器。 “快速和简单”并...

    netty-4.0.28.Final

    Netty是由JBOSS提供的一个java开源框架。Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序dsf。...netty, 4.0.28, Final, jar包, 含源码

    Netty4.0.54英文版API文档

    Netty4.0.54英文版API文档,与官网中文档内容一致,方便用户在离线环境下,开发Netty

    netty-codec-http-4.1.27.Final-API文档-中英对照版.zip

    赠送jar包:netty-codec-http-4.1.27.Final.jar; 赠送原API文档:netty-codec-http-4.1.27.Final-javadoc.jar; 赠送源代码:netty-codec-http-4.1.27.Final-sources.jar; 赠送Maven依赖信息文件:netty-codec-...

Global site tag (gtag.js) - Google Analytics