Java搭建简单Netty开发环境入门教程

 更新时间:2021年06月25日 17:10:01   作者:xiahb_jp  
这篇文章主要介绍了Java搭建简单Netty开发环境入门教程,有详细的代码展示和maven依赖,能够帮助你快速上手Netty开发框架,需要的朋友可以参考下

下面就是准备Netty的jar包了,如果你会maven的话自然是使用maven最为方便了。只需要在pom文件中导入以下几行

<!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-all</artifactId>
      <version>4.1.16.Final</version>
    </dependency>

当然啦,不会maven的也不用愁,可以在官网直接下载jar包,点击跳转。并在编辑器中将下载的jar包引入你的lib中,就可以愉快的开始Netty开发了

下面贴一个简单的netty案例

一、 服务端代码

1. EchoServerHandler.java

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
 
@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter{
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //将客户端传入的消息转换为Netty的ByteBuf类型
        ByteBuf in = (ByteBuf) msg;
 
        // 在控制台打印传入的消息
        System.out.println(
                "Server received: " + in.toString(CharsetUtil.UTF_8)
        );
        //将接收到的消息写给发送者,而不冲刷出站消息
        ctx.write(in);
    }
 
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        // 将未处决消息冲刷到远程节点, 并且关闭该Channel
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                .addListener(ChannelFutureListener.CLOSE);
    }
 
    /**
     * 异常处理
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //打印异常栈跟踪
        cause.printStackTrace();
 
        // 关闭该Channel
        ctx.close();
    }
}

2. EchoServer.java

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 EchoServer {
    private final static int port = 8080;
 
    public static void main(String[] args) {
        start();
    }
 
    private static void start() {
        final EchoServerHandler serverHandler = new EchoServerHandler();
        // 创建EventLoopGroup
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        // 创建EventLoopGroup
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                //指定所使用的NIO传输Channel
        .channel(NioServerSocketChannel.class)
                //使用指定的端口设置套接字地址
        .localAddress(new InetSocketAddress(port))
                // 添加一个EchoServerHandler到Channle的ChannelPipeline
        .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                //EchoServerHandler被标注为@shareable,所以我们可以总是使用同样的案例
                socketChannel.pipeline().addLast(serverHandler);
            }
        });
 
        try {
            // 异步地绑定服务器;调用sync方法阻塞等待直到绑定完成
            ChannelFuture f = b.bind().sync();
            // 获取Channel的CloseFuture,并且阻塞当前线程直到它完成
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 优雅的关闭EventLoopGroup,释放所有的资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

二、 客户端代码

1. EchoClientHandler.java

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
 
@Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //当被通知Channel是活跃的时候,发送一条消息
        ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));
    }
 
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        System.out.println(
                "Client received: " + byteBuf.toString(CharsetUtil.UTF_8)
        );
    }
 
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

2. EchoClient.java

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;
 
import java.net.InetSocketAddress;
 
public class EchoClient {
    private final static String HOST = "localhost";
    private final static int PORT = 8080;
 
    public static void start() {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(HOST, PORT))
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new EchoClientHandler());
                    }
                });
        try {
            ChannelFuture f = bootstrap.connect().sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }
 
    public static void main(String[] args) {
        start();
    }
}

先后运行EchoServer.java和EchoClient.java.如果控制台分别打印了

Server received: Netty rocks!

Client received: Netty rocks!

那么恭喜你,你已经可以开始netty的开发了。

点击查看Netty结合Protobuf编解码

到此这篇关于Java搭建简单Netty开发环境入门教程的文章就介绍到这了,更多相关Java搭建Netty环境内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java整合onlyoffice的各种踩坑记录

    java整合onlyoffice的各种踩坑记录

    这篇文章主要给大家介绍了关于java整合onlyoffice的各种踩坑,OnlyOffice是一种强大的在线协作软件,专为企业和个人设计,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2023-07-07
  • JAVA 对50取余数的五种方法试下

    JAVA 对50取余数的五种方法试下

    在数学计算中经常会遇到余数,本文主要介绍了JAVA 对50取余数的五种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-03-03
  • Spring中的StopWatch记录操作时间代码实例

    Spring中的StopWatch记录操作时间代码实例

    这篇文章主要介绍了Spring中的StopWatch记录操作时间代码实例,spring-framework提供的一个StopWatch类可以做类似任务执行时间控制,也就是封装了一个对开始时间,结束时间记录操作的Java类,需要的朋友可以参考下
    2023-11-11
  • Flink实战之实现流式数据去重

    Flink实战之实现流式数据去重

    流式数据是一种源源不断产生的数据,本文探索了一种流式大数据的实时去重方法,不一定适用于所有场景,不过或许可以给面对相似问题的你一点点启发,
    2025-03-03
  • java中为什么要谨慎使用Arrays.asList、ArrayList的subList

    java中为什么要谨慎使用Arrays.asList、ArrayList的subList

    这篇文章主要介绍了java中为什么要谨慎使用Arrays.asList、ArrayList的subList,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-02-02
  • 详解Spring系列之@ComponentScan自动扫描组件

    详解Spring系列之@ComponentScan自动扫描组件

    这篇文章主要介绍了Spring @ComponentScan自动扫描组件使用,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-06-06
  • Java 批量文件压缩导出并下载到本地示例代码

    Java 批量文件压缩导出并下载到本地示例代码

    这篇文章主要介绍了Java 批量文件压缩导出并下载到本地示例代码,实现思路首先要把zip流写入到http响应输出流中,再把excel的流写入zip流中,具体示例代码,大家通过本文学习吧
    2017-12-12
  • Springboot 实现Server-Sent Events的项目实践

    Springboot 实现Server-Sent Events的项目实践

    本文介绍了在Spring Boot中实现Server-Sent Events(SSE),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-12-12
  • SpringBoot与Redis的令牌主动失效机制实现

    SpringBoot与Redis的令牌主动失效机制实现

    本文详细介绍了基于SpringBoot和Redis实现令牌主动失效机制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-12-12
  • 使用java -jar命令启动Spring Boot应用时指定特定配置文件的几种实现方式

    使用java -jar命令启动Spring Boot应用时指定特定配置文件的几种实现方式

    这篇文章主要介绍了在使用java-jar命令启动SpringBoot应用时,指定特定配置文件的几种方式,文中通过代码介绍的非常详细,对大家的学习或者工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2025-01-01

最新评论