码迷,mamicode.com
首页 > 其他好文 > 详细

demo

时间:2019-10-08 19:01:13      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:line   util   bmc   net   nios   mes   image   oev   netty   

使用Idea加Gradle构建一个Netty项目

New Project -> Gradle -> Next

技术图片技术图片build.gradle 相当于maven的pom文件 可以去maven中央仓库寻找依赖

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

apply plugin: 'java'
//配置JDK的版本号
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    maven {
        //配置阿里云的仓库下载速度飞快
        url "https://maven.aliyun.com/nexus/content/groups/public"
    }
    mavenCentral()
}


dependencies {
    //将拷贝的依赖复制到这里是不是比maven简洁
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile group: 'io.netty', name: 'netty-all', version: '4.1.39.Final'
}

编写代码

public class TestServer {

    public static void main(String[] args) throws InterruptedException {
        //定义两个事件组
        //接收连接但是不对连接做任何处理会把事情交给workerGroup去做
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //真正处理连接的
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try{
            //启动服务
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new TestServerInitializer());
            //绑定端口
            ChannelFuture sync = serverBootstrap.bind(8899).sync();
            sync.channel().closeFuture().sync();
        }finally {
            //优雅的关闭Netty
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
public class TestServerInitializer extends ChannelInitializer<SocketChannel>{

    /**
     * 连接一旦被创建就会调用这个方法,添加自定义的处理器
     * @param ch
     * @throws Exception
     */
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("httpServerCodec",new HttpServerCodec());
        pipeline.addLast("testHttpServerHandler",new TestHttpServerHandler());
    }
}
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    /**
     * 读取客户端所发出的请求,并响应到客户端的方法
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        if (msg instanceof HttpRequest) {
            ByteBuf content = Unpooled.copiedBuffer("Hello World!", 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);
        }
    }
}

请求 http://localhost:8899 响应Hello World!

demo

标签:line   util   bmc   net   nios   mes   image   oev   netty   

原文地址:https://www.cnblogs.com/smallwolf/p/11636902.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!