基于netty构建http服务器

基于Netty构建Http服务的流程如下:

  1. Client向Server发送http请求。
  2. Server端对http请求进行解析。
  3. Server端向Client发送http响应。
  4. Client对http响应进行解析。

流程图如下:

服务器端实现

package com.morris.netty.protocol.http;import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
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.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;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;@Slf4j
public class Server {private static final int port = 8899;public static void main(String[] args) 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>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ch.pipeline().addLast(new HttpRequestDecoder()); // 请求消息解码器ch.pipeline().addLast(new HttpObjectAggregator(65536));// 目的是将多个消息转换为单一的request或者response对象ch.pipeline().addLast(new HttpResponseEncoder());//响应编码器ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {FullHttpRequest request = (FullHttpRequest) msg;log.info("method:{}", request.method().name());log.info("uri:{}", request.uri());log.info("content:{}", request.content().toString(CharsetUtil.UTF_8));FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");ByteBuf buffer = Unpooled.copiedBuffer("<h3>hello world</h3>", CharsetUtil.UTF_8);response.content().writeBytes(buffer);buffer.release();request.release();ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);}});// 业务逻辑}});ChannelFuture future = b.bind("127.0.0.1", port).sync();log.info("HTTP服务器启动,网址是 : " + "http://127.0.0.1:" + port);future.channel().closeFuture().sync();} finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}
}

在浏览器输入http://127.0.0.1:8899就可以看到页面显示hello world

客户端实现

package com.morris.netty.protocol.http;import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;@Slf4j
public class Client {public static void main(String[] args) throws InterruptedException {EventLoopGroup workerGroup = new NioEventLoopGroup();try {Bootstrap b = new Bootstrap();b.group(workerGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer() {@Overrideprotected void initChannel(Channel ch) throws Exception {ch.pipeline().addLast(new HttpResponseDecoder()); // 响应解码器ch.pipeline().addLast(new HttpObjectAggregator(65536));ch.pipeline().addLast(new HttpRequestEncoder()); // 请求编码器ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {FullHttpResponse httpResponse = (FullHttpResponse)msg;log.info("status:{}", httpResponse.status());log.info("headers:{}", httpResponse.headers());log.info("body:{}", httpResponse.content().toString(CharsetUtil.UTF_8));httpResponse.release();}@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");// 构建http请求request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);request.headers().set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());// 发送http请求ctx.writeAndFlush(request);}});}});// 启动 server.ChannelFuture f = b.connect("127.0.0.1", 8899).sync();// 等待socket关闭f.channel().closeFuture().sync();} finally {workerGroup.shutdownGracefully();}}
}

基于netty构建http服务器相关推荐

  1. Netty构建游戏服务器(一)--基本概念与原理

    一,Netty是什么 1,Netty是由 JBOSS 提供的一个 java开源 框架. 2,Netty是JAR包,一般使用ALL-IN-ONE的JAR包就可以开发了. 3,Netty不需要运行在Tom ...

  2. SuperDog——一个基于netty的web服务器开发项目

      项目GitHub地址:https://github.com/HelloWorld-Ian/SuperDog   这是我在实习期间开发的一个项目demo,简单来说是一个基于netty框架的web服务 ...

  3. 基于Netty的http服务器

    2019独角兽企业重金招聘Python工程师标准>>> 根据netty一个官方例子改编 //html文件位置 public class Config {public static S ...

  4. 网络|基于Netty构建的高性能车辆网项目实现(一)

    本文主要做技术分享,如有侵权请通知作者删除 项目背景 该项目是d市的政府项目,需要从n(n>10000)台公交车中收集车上数据,包括驱动.电池.发动机.报警等共计100余种车辆信息,需要基于国标 ...

  5. ktor框架用到了netty吗_教你如何构建异步服务器和客户端的 Kotlin 框架 Ktor

    Ktor 是一个使用 Kotlin 以最小的成本快速创建 Web 应用程序的框架. Ktor 是一个用于在连接系统(connected systems)中构建异步服务器和客户端的 Kotlin 框架. ...

  6. java web netty_基于Netty的非Servlet规范 JavaWeb框架及高性能 Java服务器

    Bay 一个非Servlet规范的JavaWeb框架,包括一个基于Netty的高性能服务器. ##介绍 这是一个基于Netty实现的非Servlet规范的Web服务器,由于底层设计经验不足,所以实际上 ...

  7. Netty学习笔记(五) 使用Netty构建静态网页服务器

    昨天在继续完善基于Netty构建的聊天室系统的过程中,发现了一个有意思的知识点,特此拿来做一个简单的静态网页服务器,好好的玩一玩Netty. 但是不管怎么说利用netty实现各种功能的流程都是类似的 ...

  8. dtu tcp java_SpringBoot 2 整合 Netty 实现基于 DTU 的 TCP 服务器 之 客户端

    使用netty不是一天两天了,但是使用netty和DTU通讯还是第一次,接下来要做DTU的通讯协议,对接工作还没有正式开始,只收到一个简单的DTU协议文档,里面的内容大概是下面表格中的样子. 位数 内 ...

  9. netty 游戏服务器框图_基于Netty和WebSocket协议实现Web端自动打印订单服务方法与流程...

    本发明涉及电子商务技术领域,尤其涉及一种基于netty和websocket协议实现web端自动打印订单服务方法. 背景技术: 电子商务是以信息网络技术为手段,以商品交换为中心的商务活动:也可理解为在互 ...

  10. 一款基于Netty开发的WebSocket服务器

    代码地址如下: http://www.demodashi.com/demo/13577.html 一款基于Netty开发的WebSocket服务器 这是一款基于Netty框架开发的服务端,通信协议为W ...

最新文章

  1. CVPR2020 | 真实场景中的玻璃检测,有趣的应用
  2. numpy中的tile函数
  3. 刘晓艳2021英语语法句型结构总结1之简单句型结构
  4. 带有Spring,Hibernate,Akka,Twitter Bootstrap,Apache Tiles和jQuery的Maven Web项目Kickstarter代码库...
  5. Java编程之反射中的注解详解
  6. 【Java】探究Java实现多接口时同名方法冲突问题
  7. wxpython使窗口重新显示出来_wxPython实现窗口在任务栏中闪烁
  8. 虚拟化与私有云的区别
  9. python中goto如何使用,基于python goto的正确用法说明
  10. 地图整饰-框架与格网
  11. 最新android APP框架介绍
  12. 1.1 线性方程组(线性代数及其应用-第5版-系列笔记)
  13. ECSHOP二次开发之给商品增加新字段
  14. 器件基础知识——电阻
  15. 高电平复位还是低电平复位?
  16. 风控策略的自动化生成-利用决策树分分钟生成上千条策略
  17. Linux 设置开机自启动
  18. spark.read.option参数
  19. 今天接到东南融通的面试电话,请问下个人一些具体情况
  20. Win10同一路由器下共享打印机

热门文章

  1. 产品必备-产品FDD模板(PRD)
  2. Unity中的Assetbundle,Unity基础知识学习一
  3. hdfs命令,hadoop基本常用命令
  4. win7系统蓝屏修复工具如何使用
  5. 景观设计建模中最常用的SU插件有哪些?
  6. 单播、多播(组播)和广播的区别
  7. 可曾听闻【大话】二字
  8. 面向对象的oop编程思想
  9. 机器人动力学建模之刚体动力学基础学习
  10. Python-snap7 安装和测试