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

处理成功~


相关文章
Netty实战: HTTP文件列表服务器
Netty实战: HTTP文件列表服务器
371 0
|
Go
在golang中发起http请求以获取访问域名的ip地址实例(使用net, httptrace库)
这只是追踪我们的行程的简单方法,不过希望你跟着探险家的脚步,即使是在互联网的隧道中,也可以找到你想去的地方。接下来就是你的探险之旅了,祝你好运!
827 26
|
前端开发 网络协议 应用服务中间件
Netty基础—7.Netty实现消息推送服务
本文详细介绍了如何使用Netty实现HTTP服务器、WebSocket以及基于WebSocket的消息推送系统。首先,通过解析HTTP请求和响应消息,展示了Netty在性能和可靠性上的优势,并提供了具体代码示例。接着,分析了HTTP协议的弊端及Ajax短轮询的不足,引出WebSocket全双工通信的优势,包括连接建立、数据处理逻辑与ping-pong探测等。最后,构建了一个完整的消息推送系统,涵盖PushServer、运营客户端与浏览器客户端的交互过程,实现了全连接推送和实时消息传递。
|
Java 开发者 索引
Netty基础—6.Netty实现RPC服务
本文详细介绍了RPC(远程过程调用)的相关概念及其实现细节,涵盖动态代理、Netty客户端和服务端处理、编码解码器以及超时功能的实现。
|
Java 网络架构 Kotlin
kotlin+springboot入门级别教程,教你如何用kotlin和springboot搭建http
本文是一个入门级教程,介绍了如何使用Kotlin和Spring Boot搭建HTTP服务,并强调了Kotlin的空安全性特性。
634 8
kotlin+springboot入门级别教程,教你如何用kotlin和springboot搭建http
|
JSON Dart 前端开发
鸿蒙应用开发从入门到入行 - 篇7:http网络请求
在本篇文章里,您将掌握鸿蒙开发工具DevEco的基本使用、ArkUI里的基础组件,并通过制作一个简单界面掌握使用
1398 8
使用Netty实现文件传输的HTTP服务器和客户端
本文通过详细的代码示例,展示了如何使用Netty框架实现一个文件传输的HTTP服务器和客户端,包括服务端的文件处理和客户端的文件请求与接收。
624 1
使用Netty实现文件传输的HTTP服务器和客户端
Netty 与硬件设备交互,下行命令时(服务对设备),如何等待设备响应,再进行业务操作解决方案
Netty 与硬件设备交互,下行命令时(服务对设备),如何等待设备响应,再进行业务操作解决方案
585 1
|
缓存 数据安全/隐私保护 UED
代理服务器在HTTP请求中的应用:Ruby实例
代理服务器在HTTP请求中的应用:Ruby实例
|
Java 应用服务中间件 Apache
Apache HTTP配置反向代理入门
Apache HTTP配置反向代理入门
907 0
Apache HTTP配置反向代理入门