netty框架

Netty的官网netty.io

Netty is an asynchronous event-driven network application framework

首页的上述字符可看出netty是一个异步事件驱动的网络应用框架

Netty是非阻塞的客户端服务器框架,底层基于NIO,将每个请求分成不同的阶段,不同的阶段开不同的线程,阶段与阶段之间是通过事件的异步通信来沟通的。

netty框架_第1张图片

Protocol Buffers是谷歌提供的可序列化和扩展化的一个工具,自己可以定义数据结构,可使用各种各样的语言从各种各样的数据流中读取数据。其只支持Java python c++

http:短链接 WebSocket:长链接

RPC框架

Netty:大文件传输支持

Netty建议用书Netty in Action

netty框架_第2张图片

下书是5.0,但5.0被废弃掉了

 

netty框架_第3张图片

gradle:比maven好用,配置内容少,较少了网络传输的消耗。其也是用maven库,只不过更轻量,更强大。

新建项目选java-gradle

建好后的项目含有bulid.gradle和srtting.gradle其中的bulid.gradle相当于maven项目中的pom.xml文件,文件本身是进行依赖管理和项目构建最为核心的文件。

netty框架_第4张图片

netty框架_第5张图片

14~15行其实与上一张图的14~15行相同,中间的15行代码是从searh.maven.org中找到netty-all的4.1.0版本的Gradle Groovy DSL,用于将jar包下载到本地。

package com.hegang.firstDemo;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Creat By ${侯某某} on 2019/11/21
 */

public class TestServer {
   public static void main(String[] args) throws InterruptedException {
       NioEventLoopGroup bossgroup = new NioEventLoopGroup();
       NioEventLoopGroup workerGroup = new NioEventLoopGroup();
       try {

           ServerBootstrap ss = new ServerBootstrap();
           //前面用于接收请求 后面用给来数据处理
           ss.group(bossgroup,workerGroup)
                   .channel(NioServerSocketChannel.class)//只链接一个通道,通过反射创建实例
                   .childHandler(new TestServerInitializer());//子处理器,也就是请求到来后由自己所编写的处理器


           //绑定端口 sync是实时更新,此方法会抛出异常
           ChannelFuture channelFutur = ss.bind(8899).sync();
           //关闭监听
           channelFutur.channel().closeFuture().sync();
       } finally {
           bossgroup.shutdownGracefully();
           workerGroup.shutdownGracefully();

       }
   }
}
-----------------------------------------------------
package com.hegang.firstDemo;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;

/**
 * Creat By ${侯某某} on 2019/11/21
 */

public class TestServerInitializer extends ChannelInitializer {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();//获取链接通道上面的管道,在上面加拦截器,每个拦截器来处理请求
        pipeline.addLast("系统自带的httpServerCodec",new HttpServerCodec());//在管道的最后面加一个组件,这个组件是netty提供的一个处理器
        pipeline.addLast("我的TestHttpServerHandler",new TestHttpServerHandler());//在管道的最后面加一个组件,这个组件是netty提供的一个处理器

    }
}
---------------------------------------------------
package com.hegang.firstDemo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * Creat By ${侯某某} on 2019/11/21
 * 前面的处理器是netty自带的,此类我们来自己定义一个处理器
 */

public class TestHttpServerHandler extends SimpleChannelInboundHandler {


    //此方法读取客户端发送过来的请求,并且给客户端返回响应的请求
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {


    //流程进入到这个方法,说明请求已经过来了,我们要把请求构建出来,并给与响应
        if(msg instanceof HttpRequest) {
            ByteBuf content = Unpooled.copiedBuffer("hello netty", CharsetUtil.UTF_8);
            //构造响应,向客户端返回版本,状态,内容
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            //设置响应的头部响应内容的类型,和响应内容的长度
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

            //将响应返回给客户端
            //需要写并且刷新
            ctx.writeAndFlush(response);

        }}
    }

在编写完上述netty代码后 在在浏览器输入http://localhost:8899发现页面一直加载不出来,运行服务器端后,发现是中文注解出现报错问题,后再在网上查到加中文注释的注解(下面第一行)还是行不通,

 

netty框架_第6张图片

 

于是查询gardle的注解问题 最后修改了build.gardle文件才得以解决

plugins {
    id 'java'
}

group 'com.hegang'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8//编译级别
targetCompatibility =1.8

repositories {//这里是如果jar包没有的话,我们的取包位置
    mavenCentral()//maven仓库
}

tasks.withType(JavaCompile) {

    options.encoding = "UTF-8"

}

//因为junit4.12找不到,故在网上找到下段代码加入
allprojects {
    repositories {
        jcenter { url "http://jcenter.bintray.com/" }
        google()
        maven { url 'http://repol.maven.org/maven2' }
    }
}

dependencies {
//    testCompile group: 'junit', name: 'junit', version: '4.12'
// //描述了项目中的各种依赖testCompile测试编译
    compile(
            "io.netty:netty-all:4.1.10.Final"
    )
}


现打开浏览器可看到

netty框架_第7张图片

netty框架_第8张图片

 

 

 

 

你可能感兴趣的:(java)