• SpringBoot + Netty初体验


    一,引入pom依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
    
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.45.Final</version>
        </dependency>
    </dependencies>
                

    二,搭建netty-server服务端

    package com.example.netty.server;
    
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelOption;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    import lombok.extern.slf4j.Slf4j;
    
    import java.net.InetSocketAddress;
    
    /**
     * 服务启动监听器
     **/
    @Slf4j
    public class NettyServer {
    
        public void start(InetSocketAddress socketAddress) {
            //new 一个主线程组
            EventLoopGroup bossGroup = new NioEventLoopGroup(1);
            //new 一个工作线程组
            EventLoopGroup workGroup = new NioEventLoopGroup(200);
            ServerBootstrap bootstrap = new ServerBootstrap()
                    .group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ServerChannelInitializer())
                    .localAddress(socketAddress)
                    //设置队列大小
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    // 两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            //绑定端口,开始接收进来的连接
            try {
                ChannelFuture future = bootstrap.bind(socketAddress).sync();
                log.info("服务器启动开始监听端口: {}", socketAddress.getPort());
                future.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                //关闭主线程组
                bossGroup.shutdownGracefully();
                //关闭工作线程组
                workGroup.shutdownGracefully();
            }
        }
    }
    package com.example.netty.server;
    
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import lombok.extern.slf4j.Slf4j;
    
    /**
     * netty服务端处理器
     **/
    @Slf4j
    public class NettyServerHandler extends ChannelInboundHandlerAdapter {
        /**
         * 客户端连接会触发
         */
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            log.info("Channel active......");
        }
    
        /**
         * 客户端发消息会触发
         */
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            log.info("服务器收到消息: {}", msg.toString());
            ctx.write("你也好哦");
            ctx.flush();
        }
    
        /**
         * 发生异常触发
         */
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    }
    package com.example.netty.server;
    
    import io.netty.channel.ChannelInitializer;
    import io.netty.handler.codec.string.StringDecoder;
    import io.netty.handler.codec.string.StringEncoder;
    import io.netty.util.CharsetUtil;
    
    import io.netty.channel.socket.SocketChannel;
    
    /**
     * netty服务初始化器
     **/
    public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            //添加编解码
            socketChannel.pipeline().addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
            socketChannel.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
            socketChannel.pipeline().addLast(new NettyServerHandler());
        }
    }
    package com.example.netty.server;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    import java.net.InetSocketAddress;
    
    @SpringBootApplication
    public class NettyServerApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(NettyServerApplication.class, args);
            //启动服务端
            NettyServer nettyServer = new NettyServer();
            nettyServer.start(new InetSocketAddress("127.0.0.1", 8090));
        }
    
    }

    三,搭建netty-client客户端

    package com.example.netty.client;
    
    import io.netty.bootstrap.Bootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelOption;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.nio.NioSocketChannel;
    import lombok.extern.slf4j.Slf4j;
    
    @Slf4j
    public class NettyClient {
    
        public void start() {
            EventLoopGroup group = new NioEventLoopGroup();
            Bootstrap bootstrap = new Bootstrap()
                    .group(group)
                    //该参数的作用就是禁止使用Nagle算法,使用于小数据即时传输
                    .option(ChannelOption.TCP_NODELAY, true)
                    .channel(NioSocketChannel.class)
                    .handler(new NettyClientInitializer());
    
            try {
                ChannelFuture future = bootstrap.connect("127.0.0.1", 8090).sync();
                log.info("客户端成功....");
                //发送消息
                future.channel().writeAndFlush("你好啊");
                // 等待连接被关闭
                future.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                group.shutdownGracefully();
            }
        }
    }
    package com.example.netty.client;
    
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import lombok.extern.slf4j.Slf4j;
    
    /**
     * 客户端处理器
     **/
    @Slf4j
    public class NettyClientHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            log.info("客户端Active .....");
        }
    
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            log.info("客户端收到消息: {}", msg.toString());
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    }
    package com.example.netty.client;
    
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.handler.codec.string.StringDecoder;
    import io.netty.handler.codec.string.StringEncoder;
    
    /**
     * 客户端初始化器
     **/
    public class NettyClientInitializer extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            socketChannel.pipeline().addLast("decoder", new StringDecoder());
            socketChannel.pipeline().addLast("encoder", new StringEncoder());
            socketChannel.pipeline().addLast(new NettyClientHandler());
        }
    }
    package com.example.netty.client;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class NettyClientApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(NettyClientApplication.class, args);
            //启动netty客户端
            NettyClient nettyClient = new NettyClient();
            nettyClient.start();
        }
    
    }

    收工!

  • 相关阅读:
    【一个蒟蒻的挣扎】单源最短路(Dijkstra)
    【字符串大模拟】潜伏者—— NOIP2009原题
    【一个蒟蒻的挣扎】最长上升子序列
    【球的序列】——最长上升子序列
    【洛谷P1886】滑动窗口——单调队列
    【实时更新】你永远都不会想到上了考场会犯什么样的**错误——汇总
    【洛谷P1816】忠诚——ST表做法
    【一道来自老师的题的题解】equip——奇妙的最短路
    【洛谷P1119题解】灾后重建——(floyd)
    济南集训总结
  • 原文地址:https://www.cnblogs.com/gaomanito/p/15919742.html
Copyright © 2020-2023  润新知