Netty入门实例-Http服务

╰+攻爆jí腚メ 2023-06-25 10:27 86阅读 0赞

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

Http服务

1.需求

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

2.创建服务端handler

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

  1. package com.dpb.netty.http;
  2. import io.netty.buffer.ByteBuf;
  3. import io.netty.buffer.Unpooled;
  4. import io.netty.channel.ChannelHandlerContext;
  5. import io.netty.channel.SimpleChannelInboundHandler;
  6. import io.netty.handler.codec.http.*;
  7. import io.netty.util.CharsetUtil;
  8. import java.net.URI;
  9. /** * @program: netty4demo * @description: * @author: 波波烤鸭 * @create: 2019-12-24 16:49 */
  10. public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
  11. /** * 读取客户端发送的数据 * @param context * @param httpObject * @throws Exception */
  12. @Override
  13. protected void channelRead0(ChannelHandlerContext context, HttpObject httpObject) throws Exception {
  14. if(httpObject instanceof HttpRequest){
  15. // 判断是否是 Http请求
  16. System.out.println(context.pipeline().hashCode());
  17. System.out.println(httpObject.hashCode());
  18. System.out.println(context.channel().remoteAddress());
  19. HttpRequest request = (HttpRequest) httpObject;
  20. URI uri = new URI(request.uri());
  21. if("/favicon.ico".equals(uri.getPath())){
  22. System.out.println("请求了 favicon.ico 。。");
  23. return ;
  24. }
  25. ByteBuf byteBuf = Unpooled.copiedBuffer("hello,我是服务端...", CharsetUtil.UTF_8);
  26. FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,byteBuf);
  27. response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=utf-8");
  28. response.headers().set(HttpHeaderNames.CONTENT_LENGTH,byteBuf.readableBytes());
  29. context.writeAndFlush(response);
  30. }
  31. }
  32. }

3.创建服务端

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

  1. package com.dpb.netty.http;
  2. import io.netty.bootstrap.ServerBootstrap;
  3. import io.netty.channel.*;
  4. import io.netty.channel.nio.NioEventLoopGroup;
  5. import io.netty.channel.socket.ServerSocketChannel;
  6. import io.netty.channel.socket.SocketChannel;
  7. import io.netty.channel.socket.nio.NioServerSocketChannel;
  8. import io.netty.handler.codec.http.HttpServerCodec;
  9. /** * @program: netty4demo * @description: * @author: 波波烤鸭 * @create: 2019-12-24 16:45 */
  10. public class TestHttpServer {
  11. public static void main(String[] args) {
  12. EventLoopGroup bossGroup = new NioEventLoopGroup();
  13. EventLoopGroup workGroup = new NioEventLoopGroup();
  14. try{
  15. ServerBootstrap bootstrap = new ServerBootstrap();
  16. bootstrap.group(bossGroup,workGroup)
  17. .channel(NioServerSocketChannel.class)
  18. .childHandler(new ChannelInitializer<SocketChannel>() {
  19. @Override
  20. protected void initChannel(SocketChannel sc) throws Exception {
  21. ChannelPipeline pipeline = sc.pipeline();
  22. // 添加对应的服务端编解码器
  23. pipeline.addLast("MyHttpServerCodec",new HttpServerCodec());
  24. // 添加对应的处理器
  25. pipeline.addLast("MyTestHttpServerHandler",new TestHttpServerHandler());
  26. }
  27. });
  28. System.out.println("服务器启动了...");
  29. ChannelFuture future = bootstrap.bind(8666).sync();
  30. future.addListener(new ChannelFutureListener() {
  31. @Override
  32. public void operationComplete(ChannelFuture channelFuture) throws Exception {
  33. if(future.isSuccess()){
  34. System.out.println("请求处理成功了....");
  35. }
  36. }
  37. });
  38. future.channel().closeFuture().sync();
  39. }catch (Exception e){
  40. }finally {
  41. bossGroup.shutdownGracefully();
  42. workGroup.shutdownGracefully();
  43. }
  44. }
  45. }

4. 效果测试

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

在这里插入图片描述

在这里插入图片描述

处理成功~

发表评论

表情:
评论列表 (有 0 条评论,86人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Netty入门实例 TCP服务

    基于Netty开发一个入门程序,主要功能:服务端启动后监听一个端口,客户端启动后会给服务端发送一条消息,服务端收到后通过Handler读取消息,进行处理,读取完通过Handle