Netty第一个入门实例-TCP服务

简介: 本文我们来写第一个Netty的入门实例,一个TCP服务案例。


Netty入门案例

1. 案例需求

  1. 创建Netty 服务器在 6668 端口监听
  2. 创建Netty客户端,客户端能发送消息给服务器 “hello, 服务器~”
  3. 服务器可以回复消息给客户端 “hello, 客户端~”

目的:对Netty 线程模型 有一个初步认识, 便于理解Netty 模型理论

2.创建maven项目

  通过eclipse或者IDEA创建一个普通的maven项目即可

3.导入依赖

  引入相关的maven坐标

<dependency>
   <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.20.Final</version>
</dependency>

4.创建服务端Handler

  创建服务端的handler,主要是处理客户端提交的请求的。

package com.dpb.netty.tcp;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
/**
 * @program: netty4demo
 * @description:
 * @author: 波波烤鸭
 * @create: 2019-12-23 11:24
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    /**
     * 读取客户端发送来的数据
     * @param ctx ChannelHandler的上下文对象 有管道 pipeline 通道 channel 和 请求地址 等信息
     * @param msg 客户端发送的具体数据
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("客户端请求到了..." + ctx.channel().remoteAddress());
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("客户端发送的数据是:" +buf.toString(CharsetUtil.UTF_8));
    }
    /**
     * 读取客户端发送数据完成后的方法
     *    在本方法中可以发送返回的数据
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        // writeAndFlush 是组合方法
        ctx.writeAndFlush(Unpooled.copiedBuffer("你好啊,客户端....^_^",CharsetUtil.UTF_8));
    }
}

5.创建服务端

  创建服务端

package com.dpb.netty.simple;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
 * @program: netty4demo
 * @description:
 * @author: 波波烤鸭
 * @create: 2019-12-23 11:15
 */
public class NettyServerDemo {
    public static void main(String[] args) {
        // 创建对应的 线程池
        // 创建Boss group
        EventLoopGroup boosGroup = new NioEventLoopGroup(1);
        // 创建 workgroup
        EventLoopGroup workGroup = new NioEventLoopGroup();
        // 创建对应的启动类
        ServerBootstrap bootstrap = new ServerBootstrap();
        try{
            // 设置相关的配置信息
            bootstrap.group(boosGroup,workGroup) // 设置对应的线程组
                    .channel(NioServerSocketChannel.class) // 设置对应的通道
                    .option(ChannelOption.SO_BACKLOG,1024) // 设置线程的连接个数
                    .childHandler(new ChannelInitializer<SocketChannel>() { // 设置
                        /**
                         * 给pipeline 设置处理器
                         * @param socketChannel
                         * @throws Exception
                         */
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new NettyServerHandler());
                        }
                    });
            System.out.println("服务启动了....");
            // 绑定端口  启动服务
            ChannelFuture channelFuture = bootstrap.bind(6668).sync();
            // 对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
        }finally {
            // 优雅停服
            boosGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}

6.创建客户端Handler

  客户端handler主要是发送请求给客户端及处理服务端返回的信息。

package com.dpb.netty.simple;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
/**
 * @program: netty4demo
 * @description:
 * @author: 波波烤鸭
 * @create: 2019-12-23 11:36
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    /**
     * 连接上服务的回调方法
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 发送数据
        System.out.println("连接上了 服务器....");
        ctx.writeAndFlush(Unpooled.copiedBuffer("哈哈 你好呀!!!", CharsetUtil.UTF_8));
    }
    /**
     * 读取服务端返回的信息
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf  = (ByteBuf) msg;
        System.out.println("服务端返回的信息:" + buf.toString(CharsetUtil.UTF_8));
    }
}

7.创建客户端

  客户端用来连接服务器

package com.dpb.netty.simple;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
/**
 * @program: netty4demo
 * @description:
 * @author: 波波烤鸭
 * @create: 2019-12-23 11:31
 */
public class NettyClientDemo {
    public static void main(String[] args) {
        // 客户端就只需要创建一个 线程组了
        EventLoopGroup loopGroup = new NioEventLoopGroup();
        // 创建 启动器
        Bootstrap bootstrap = new Bootstrap();
        try{
            // 设置相关的参数
            bootstrap.group(loopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new NettyClientHandler());
                        }
                    });
            // 连接服务
            ChannelFuture future = bootstrap.connect("localhost",6668).sync();
            // 对服务关闭 监听
            future.channel().closeFuture().sync();
        }catch (Exception e){
        }finally {
            loopGroup.shutdownGracefully();
        }
    }
}

8.测试

  先启动服务器,然后再启动客户端,然后看下面的效果,实现了我们的要求

image.png

方案再说明

  1. Netty 抽象出两组线程池,BossGroup 专门负责接收客户端连接,WorkerGroup 专门负责网络读写操作。
  2. NioEventLoop 表示一个不断循环执行处理任务的线程,每个 NioEventLoop 都有一个 selector,用于监听绑定在其上的 socket 网络通道。
  3. NioEventLoop 内部采用串行化设计,从消息的读取->解码->处理->编码->发送,始终由 IO 线程 NioEventLoop 负责

NioEventLoopGroup 下包含多个 NioEventLoop

每个 NioEventLoop 中包含有一个 Selector,一个 taskQueue

每个 NioEventLoop 的 Selector 上可以注册监听多个 NioChannel

每个 NioChannel 只会绑定在唯一的 NioEventLoop 上

每个 NioChannel 都绑定有一个自己的 ChannelPipeline

好了netty的第一个入门案例就到此了,具体的代码解释请多看代码中的注释,有不清楚的欢迎留言交流 O(∩_∩)O哈哈~


相关文章
|
1月前
|
缓存 网络协议 算法
Netty的基础入门(上)
Netty的基础入门(上)
121 0
|
1月前
|
网络协议 Java Maven
基于Netty实现TCP通信
基于Netty实现TCP通信
44 0
|
1月前
|
缓存 网络协议 算法
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析
163 0
|
1月前
|
编解码 缓存 移动开发
TCP粘包/拆包与Netty解决方案
TCP粘包/拆包与Netty解决方案
57 0
|
1月前
|
网络协议
Netty实现TCP通信
Netty实现TCP通信
58 0
|
1月前
|
网络协议 Java 物联网
Spring Boot与Netty打造TCP服务端(解决粘包问题)
Spring Boot与Netty打造TCP服务端(解决粘包问题)
169 1
|
1月前
|
设计模式 网络协议 算法
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析(一)
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析(一)
109 1
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析(一)
|
1月前
|
消息中间件 缓存 Java
《跟闪电侠学Netty》阅读笔记 - 开篇入门Netty
《跟闪电侠学Netty》阅读笔记 - 开篇入门Netty
118 0
|
1月前
|
Java
Netty实现HTTP服务
Netty实现HTTP服务
42 0
|
1月前
|
缓存 网络协议 算法
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析(二)
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析
70 1