Netty入门实例-Http服务

简介: 本文我们继续来实现Netty的第二个入门案例,一个Http服务。


Http服务

1.需求

  1. Netty 服务器在 6668 端口监听
  2. 浏览器发出请求 "http://localhost:6668/ "
  3. 服务器可以回复消息给客户端 "Hello! 我是服务器 5 " , 并对特定请求资源进行过滤.

2.创建服务端handler

  在handler中我们对浏览器提交的Http请求做出处理

package com.dpb.netty.http;
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;
import java.net.URI;
/**
 * @program: netty4demo
 * @description:
 * @author: 波波烤鸭
 * @create: 2019-12-24 16:49
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    /**
     * 读取客户端发送的数据
     * @param context
     * @param httpObject
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext context, HttpObject httpObject) throws Exception {
        if(httpObject instanceof HttpRequest){
            // 判断是否是 Http请求
            System.out.println(context.pipeline().hashCode());
            System.out.println(httpObject.hashCode());
            System.out.println(context.channel().remoteAddress());
            HttpRequest request = (HttpRequest) httpObject;
            URI uri = new URI(request.uri());
            if("/favicon.ico".equals(uri.getPath())){
                System.out.println("请求了 favicon.ico 。。");
                return ;
            }
            ByteBuf byteBuf = Unpooled.copiedBuffer("hello,我是服务端...", CharsetUtil.UTF_8);
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,byteBuf);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=utf-8");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,byteBuf.readableBytes());
            context.writeAndFlush(response);
        }
    }
}

3.创建服务端

  创建服务端程序,创建服务。

package com.dpb.netty.http;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
/**
 * @program: netty4demo
 * @description:
 * @author: 波波烤鸭
 * @create: 2019-12-24 16:45
 */
public class TestHttpServer {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try{
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel sc) throws Exception {
                            ChannelPipeline pipeline = sc.pipeline();
                            // 添加对应的服务端编解码器
                            pipeline.addLast("MyHttpServerCodec",new HttpServerCodec());
                            // 添加对应的处理器
                            pipeline.addLast("MyTestHttpServerHandler",new TestHttpServerHandler());
                        }
                    });
            System.out.println("服务器启动了...");
            ChannelFuture future = bootstrap.bind(8666).sync();
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if(future.isSuccess()){
                        System.out.println("请求处理成功了....");
                    }
                }
            });
            future.channel().closeFuture().sync();
        }catch (Exception e){
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}

4. 效果测试

  启动服务器,返回在浏览器地址栏中输入 http://localhost:8666/index.html

image.png

image.png

处理成功~


相关文章
|
3月前
|
缓存 网络协议 算法
Netty的基础入门(上)
Netty的基础入门(上)
153 0
|
7天前
|
缓存 数据安全/隐私保护 UED
代理服务器在HTTP请求中的应用:Ruby实例
代理服务器在HTTP请求中的应用:Ruby实例
|
20天前
|
运维 Serverless API
Serverless 应用引擎使用问题之如何开发HTTP服务
阿里云Serverless 应用引擎(SAE)提供了完整的微服务应用生命周期管理能力,包括应用部署、服务治理、开发运维、资源管理等功能,并通过扩展功能支持多环境管理、API Gateway、事件驱动等高级应用场景,帮助企业快速构建、部署、运维和扩展微服务架构,实现Serverless化的应用部署与运维模式。以下是对SAE产品使用合集的概述,包括应用管理、服务治理、开发运维、资源管理等方面。
|
12天前
|
网络协议 Go
【go笔记】简单的http服务
【go笔记】简单的http服务
|
1月前
|
消息中间件 API 数据库
在微服务架构中,每个服务通常都是一个独立运行、独立部署、独立扩展的组件,它们之间通过轻量级的通信机制(如HTTP/RESTful API、gRPC等)进行通信。
在微服务架构中,每个服务通常都是一个独立运行、独立部署、独立扩展的组件,它们之间通过轻量级的通信机制(如HTTP/RESTful API、gRPC等)进行通信。
|
2月前
|
Dubbo 前端开发 Java
Dubbo3 服务原生支持 http 访问,兼具高性能与易用性
本文展示了 Dubbo3 triple 协议是如何简化从协议规范与实现上简化开发测试、入口流量接入成本的,同时提供高性能通信、面向接口的易用性编码。
16553 14
|
1月前
|
网络协议 程序员 应用服务中间件
Swoole与Go系列教程之HTTP服务的应用
PHP 曾是Web开发领域佼佼者,随着业务壮大,异步和高并发方面不足显现。Swoole 曾经尝试填补空白,但局限性也比较的明显。Go 语言的崛起,简洁语法和并发优势吸引大厂使用,吸引了大多数程序员的转型。
987 0
Swoole与Go系列教程之HTTP服务的应用
|
2月前
|
数据采集 安全
怎么筛选出好的http代理服务?
在选择好的HTTP代理服务时,关注点应包括:低重复率的IP池,确保高可用性和稳定性;完善的安全机制以保障用户信息;广泛地域覆盖,适应不同区域需求;多样化的代理类型,如共享、独享、静态和隧道代理,根据需求平衡性能与成本。考虑这些因素,可找到性价比高的HTTP代理服务。
54 5
|
1月前
|
JSON 应用服务中间件 开发工具
Ngnix的http块自定义服务日志,access.log和error.log,log_format指定日志输出格式设置
Ngnix的http块自定义服务日志,access.log和error.log,log_format指定日志输出格式设置
|
2月前
|
Java 应用服务中间件 Apache
Apache HTTP配置反向代理入门
Apache HTTP配置反向代理入门
139 0
Apache HTTP配置反向代理入门