Netty使用教程(一)

1.传输一个字符串

1. netty开发基本流程

  • 基本流程
    在这里插入图片描述- 详细流程

在这里插入图片描述标红的位置为客户端和服务端不同的地方

创建的工程名称,用驼峰命名法
内部jar包名称全部小写

  • 创建类
    在这里插入图片描述- 创建类
    在这里插入图片描述

2.分别实现客户端和服务器端

2.1 实现客户端

(1)增加Sharable注解,为了线程安全
客户端消息接收和异常处理

package com.xc.helloworld;


import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.ByteBuffer;

/**
 * @Author  Michael
 * @Date   2008/08/11   20:42
 * @Description; 通用handler,处理I/O时间
 */

@ChannelHandler.Sharable// 为了线程安全
public class HandlerClientHello extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        /**
         * @Author  Michael
         * @Date   2008/08/11   20:42
         * @Description; 处理接收到的消息
         */
    //sout
        System.out.println("接收到的消息");
    }

    
    //输入ex,增加如下异常处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        /**
         * @Author  Michael
         * @Date   2008/08/11   20:53
         * @Description; 处理I.O事件的异常
         */
        cause.printStackTrace();
        ctx.close();

    }
}

在这里插入图片描述
创建客户端启动类

package com.xc.helloworld;


import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * @Author  Michael
 * @Date   2008/08/11   20:42
 * @Description; 客户端启动类
 */
public class AppClientHello {

    private final String host;
    private final int port;

    // 右键选择generater 创建构造函数
    //或者 alt + insert建
    //实例化这个类的时候,需要传这两个参数进来

    public AppClientHello(String host, int port) {
        this.host = host;
        this.port = port;
    }


    public void run() throws Exception{

        // IO的线程池
        /**
         * @Author  Michael
         * @Date   2008/08/11   20:42
         * @Description; 配置相应的参数,提供链接到远端的方法
         */

        EventLoopGroup group = new EpollEventLoopGroup();// IO线程池
        // CTRL +ALT +T 快速输入
        try {
            Bootstrap bs = new Bootstrap();// 客户端辅助启动类
            bs.group(group)
                    .channel(NioSocketChannel.class) // 实例化一个channel
                    .remoteAddress(new InetSocketAddress(host, port))
                    .handler((new ChannelInitializer<SocketChannel>() // 进行通道初始化配置
                    {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // 内部配置handler
                            // pipeline 管道,可以看作是handler的容器
                            socketChannel.pipeline().addLast(new HandlerClientHello()); //添加自定义的handler
                        }
                    }));


            // 配置完成后,链接到远端
            // 连接到远程节点,等待连接完成
            ChannelFuture future = bs.connect().sync();

            // 发送消息到服务器,格式是utf8
            future.channel().writeAndFlush(Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8));

            // 阻塞操作,closeFuture()开启了一个channel的监听器(这期间channel在进行各项工作,知道连接断开)
            future.channel().closeFuture().sync();


        } finally {
            // 最后要释放资源,释放线程池后,彻底关闭,防止内存泄漏
            // 优雅的关闭线程池
            group.shutdownGracefully().sync();
        }

    }

    public static void main(String[] args) throws Exception{
        new AppClientHello("127.0.0.1", 1357).run();
    }

}

在这里插入图片描述

3.netty关键知识点

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值