`
iaiai
  • 浏览: 2179705 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

基于Netty4的HttpServer和HttpClient的简单实现

    博客分类:
  • J2EE
 
阅读更多
Http 消息格式:

Http request:
Method path-to-resource HTTPVersion-number
Header-name-1: value1
Header-name-2: value2

Optional request body

Http response:
HTTP/Version-number response-code response-phrase 
Header-name-1: value1
Header-name-2: value2

Optional response body

实现一个简单的Http请求及响应过程:

1、Client向Server发送http请求。

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

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

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

Netty中Http request消息格式:

Netty中Http response消息格式:

代码实例:

Http Server:
package com.netty.test;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

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 {

    private static Log log = LogFactory.getLog(HttpServer.class);
    
    public void start(int port) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                                @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) 
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

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

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

    public static void main(String[] args) throws Exception {
        HttpServer server = new HttpServer();
        log.info("Http Server listening on 8844 ...");
        server.start(8844);
    }
}

响应请求的HttpServerInboundHandler:
package com.netty.test;

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 org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

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;

public class HttpServerInboundHandler extends ChannelInboundHandlerAdapter {

    private static Log log = LogFactory.getLog(HttpServerInboundHandler.class);

    private HttpRequest request;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        if (msg instanceof HttpRequest) {
            request = (HttpRequest) msg;

            String uri = request.getUri();
            System.out.println("Uri:" + uri);
        }
        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;
            ByteBuf buf = content.content();
            System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8));
            buf.release();

            String res = "I am OK";
            FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
                    OK, Unpooled.wrappedBuffer(res.getBytes("UTF-8")));
            response.headers().set(CONTENT_TYPE, "text/plain");
            response.headers().set(CONTENT_LENGTH,
                    response.content().readableBytes());
            if (HttpHeaders.isKeepAlive(request)) {
                response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            }
            ctx.write(response);
            ctx.flush();
        }
    }

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

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error(cause.getMessage());
        ctx.close();
    }

}

Http Client:
package com.netty.test;

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();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            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();

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

            // 构建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());
            // 发送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", 8844);
    }
}

处理Server响应的HttpClientInboundHandler:
package com.netty.test;

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;

public class HttpClientInboundHandler extends ChannelInboundHandlerAdapter {

    @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(msg instanceof HttpContent)
        {
            HttpContent content = (HttpContent)msg;
            ByteBuf buf = content.content();
            System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8));
            buf.release();
        }
    }
}

参考代码:https://github.com/luxiaoxun/Code4Java
  • 大小: 17.2 KB
  • 大小: 17.6 KB
分享到:
评论

相关推荐

    netty http client & server

    在 "netty-http-server" 文件中,我们可以找到一个使用 Netty 实现的 HTTP 服务器示例,它展示了如何接收和处理 HTTP 请求。而在 "netty-http-client" 文件中,包含了一个简单的 HTTP 客户端示例,演示了如何向...

    netty4.1开发jar和api说明

    - **HttpServer** 和 **HttpClient**:提供了构建HTTP和HTTPS服务器及客户端的简便方法。 - **WebSocketServer** 和 **WebSocketClient**:支持WebSocket协议,实现双向通信。 8. **最佳实践** - **资源管理**:...

    reactor-netty-jar.zip

    通过`HttpServer`和`HttpClient`,开发者可以轻松构建响应式的Web服务和客户端。它们都基于Netty的HTTP和WebSocket实现,但包装了反应式API,使得处理HTTP请求和响应更加简洁。 五、实战应用 在实际项目中,...

    NettyHttp源码

    在Netty中,HTTP和HTTPS的实现主要依赖于两个关键组件:`HttpClient`和`HttpServer`。这些组件是Netty框架内实现HTTP/HTTPS协议的核心。 1. **NettyHttpServer**: - Netty的HttpServer允许开发者自定义处理HTTP...

    netty权威指南第二版随书示例源码

    1. **异步事件驱动**:Netty 使用非阻塞 I/O 模型,基于 Java NIO(非阻塞输入/输出)库,提高了并发性能和系统资源利用率。 2. **Channel**:Netty 中的 Channel 是连接的抽象,它可以读取和写入数据。每个 ...

    Android-http4k是一个用Kotlin编写的HTTP工具包

    4. **Clients(客户端)**: 客户端模块提供了对HTTP请求的封装,支持同步和异步操作,包括OkHttp、Apache HttpClient等。 **使用示例** 创建一个简单的HTTP服务器: ```kotlin import http4k.core.HttpHandler ...

    计算机网络管理实验报告.pdf

    - **程序文件说明**:报告中列出了包括Consumer.java、Producer.java、Netty_Server.java、Netty_Client.java、Redis.java、HttpClient.java、UrlGet.java、log4j.properties等关键程序文件及其功能描述。...

    common-tls-ssl::locked_with_key:使用TLSSSL的单向身份验证为API设置安全性以及同时使用Spring Boot的基于Java的Web服务器和客户端的相互交互身份验证的教程。 提供了不同的客户端,例如Apache HttpClient,OkHttp,Spring RestTemplate,Spring WebFlux WebClient Jetty和Netty,新旧JDK HttpClient,新旧泽西岛客户端,Google HttpClient,Unirest,Retr

    掌握两种方式的TLS :locked_with_key: 本教程将引导您完成通过TLS... 一段时间后,我发现有更多的Java客户端,并且还有一些基于Kotlin和Scala的客户端。 配置ssl / tls可能很困难,每个客户端都需要不同的设置。 我想

    java编写的浏览器和服务器

    在Java中,我们可以使用Socket编程或者基于HTTP协议的库(如Apache HttpClient或OkHttp)来实现客户端功能,而对于服务器端,可以使用内置的HTTP服务器框架,如Jetty、Tomcat或Netty。 项目中的"浏览器"部分可能...

    C#网络编程.rar

    2. 实时聊天应用:基于TCP或UDP实现即时消息传递,如简单的聊天室或多人游戏。 3. Web服务消费:使用HttpClient调用RESTful API,获取或提交数据到Web服务。 4. 数据同步:通过HTTP/HTTPS协议,实现本地数据库与...

    分布式代码rpc.rar_DEMO_caf 分布式_herselfcz9_java f4框架_分布式

    本资源包含了一个基于Java实现的简易RPC框架源码及DEMO,非常适合初学者用来学习和理解RPC的工作原理。 首先,让我们来探讨一下RPC的基本概念。RPC使得应用程序可以在不关心网络细节的情况下进行通信,隐藏了底层...

    client_server_app.rar_APP_in

    7. **Netty框架**:Netty是一个高性能、异步事件驱动的网络应用框架,常用于快速开发可维护的高性能协议服务器和客户端,支持多种协议,包括TCP、UDP和HTTP等。 8. **Spring Boot**:现代Java应用开发中,Spring ...

    Java写http代理服务器

    1. **网络编程基础**:熟悉Java的Socket编程是首要的,因为HTTP通信基于TCP/IP协议,我们需要使用Socket来建立客户端和服务器之间的连接。`java.net.Socket`和`java.net.ServerSocket`类是核心工具。 2. **HTTP协议...

    仿QQ空间风格多用户系统

    5. **网络通信**:了解HTTP协议,以及使用Netty或Apache HttpClient等库进行网络通信。 6. **缓存技术**:可能涉及到Redis等缓存技术,用于提高系统性能和用户体验。 7. **并发编程**:理解Java并发模型,如线程池、...

    非阻塞通信

    在Java中,可以使用`HttpURLConnection`或者第三方库如Apache HttpClient来实现HTTP客户端,而服务器端可以使用Servlet API或者Jetty、Netty等服务器框架来处理HTTP请求。 通过非阻塞通信,开发者可以构建高并发的...

    JAVA上百实例源码以及开源项目源代码

    Java数组倒置 简单 Java图片加水印,支持旋转和透明度设置 摘要:Java源码,文件操作,图片水印 util实现Java图片水印添加功能,有添加图片水印和文字水印,可以设置水印位置,透明度、设置对线段锯齿状边缘处理、水印...

    网络编程学习资源及解释

    网络编程是计算机科学中的一个重要领域,它涉及到通过网络在不同设备间交换数据和实现通信的原理与技术。本文将深入探讨网络编程的核心概念,并结合提供的资源《Visual C#网络编程》(源程序),来帮助你理解和掌握...

    NetworkApp-master.rar

    - **核心类分析**:可能包含Server类负责监听和接受连接,Client类用于发起连接,以及DataTransfer类处理数据的发送和接收。 - **配置文件**:如application.properties或application.yml,用于配置服务器端口、...

    vertx-beginner:vertx中的前几行代码

    开发者将学习如何使用`HttpClient`和`HttpServer`来创建HTTP服务和客户端,以及如何处理异步响应。 4. **Async Handling**: Java 8的 CompletableFuture和Future接口将在处理异步操作时发挥关键作用。学习者会学习...

    base_server:这是服务器项目,包含一系列通用代码

    Java的Netty和Apache HttpClient库是常见的选择,它们提供了高性能的网络通信能力。 2. **数据访问层**:对于数据库操作,`base_server`可能封装了JDBC或者使用了ORM(对象关系映射)框架如Hibernate或MyBatis,以...

Global site tag (gtag.js) - Google Analytics