Netty的讲解和基本使用(SpringBoot配置netty及基础使用)

Netty

  • 是一款优秀的网络通信框架

  • Netty特点:高并发、高性能、高可用

  • Netty的优势:使用简单、功能强大、扩展灵活、超强稳定、社区活跃

  • Netty能干啥:
    基本应用 -> 根据各种通信协议,写客户端、服务器端应用
    进阶应用 -> 实现自己的HTTP服务器,FTP服务器,UDP服务器,RPC服务器、webSocket服务器、Redis的Proxy服务器,MYSQL的Proxy服务器等等。


    在这里插入图片描述
    在这里插入图片描述

依赖

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

客户端

HandlerClient.java
处理客户端IO事件

package org.example.nettyClient;

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

@ChannelHandler.Sharable
public class HandlerClient extends SimpleChannelInboundHandler {

    /**处理接收到的消息*/
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
        System.out.println("接收到达消息"+o.toString());
    }

    /**处理I/O事件的异常*/
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

AppClient.java
客户端发送信息

package org.example.nettyClient;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
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;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

public class AppClient {

    private final String host;
    private final int port;

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

    public void run() throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();//I/O线程池

        try {
            Bootstrap bootstrap = new Bootstrap();//客户端启动辅助类
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)//实例化一个Channel
                    .remoteAddress(new InetSocketAddress(host, port))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new HandlerClient());
                        }
                    });

            //连接到远程节点,等待连接完成
            ChannelFuture future=bootstrap.connect().sync();

            future.channel().writeAndFlush(Unpooled.copiedBuffer("hello word", CharsetUtil.UTF_8));
            //阻塞操作
            future.channel().closeFuture().sync();
        } finally {

            group.shutdownGracefully().sync();
        }
    }

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

服务端

HandlerServer.java

package org.example.nettyClient;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.util.CharsetUtil;

@ChannelHandler.Sharable
public class HandlerServer extends ChannelInboundHandlerAdapter {

    /**处理接收到的消息*/
    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {

        ByteBuf byteBuf= (ByteBuf) o;
        System.out.println("接收到客户端传来的消息:"+byteBuf.toString(CharsetUtil.UTF_8));

        channelHandlerContext.writeAndFlush(Unpooled.copiedBuffer("你好,我是服务端,我已经收到消息", CharsetUtil.UTF_8));
    }

    /**处理I/O事件的异常*/
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

AppServer.java

package org.example.nettyClient;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;

import java.net.InetSocketAddress;

public class AppServer {


    private final int port;

    public AppServer(int port) {

        this.port = port;
    }

    public void run() throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();//I/O线程池

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();//客户端启动辅助类
            bootstrap.group(group)
                    .channel(NioServerSocketChannel.class)//实例化一个Channel
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new HandlerServer());
                        }
                    });

            //连接到远程节点,等待连接完成
            ChannelFuture future = bootstrap.bind().sync();

            System.out.println(future.channel().localAddress()+"开启监听");
//            future.channel().writeAndFlush(Unpooled.copiedBuffer("hello word", CharsetUtil.UTF_8));
            //阻塞操作
            future.channel().closeFuture().sync();
        } finally {

            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception {
        new AppServer(8083).run();
    }
}

在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值