简单的Java实现Netty进行通信

本文介绍了如何使用Java搭建一个简单的Netty通信示例,包括准备阶段的工程结构,rpc-common、rpc-client和rpc-server模块的说明,以及依赖管理。在实现部分,详细解释了Netty对象的序列化、NetyServer和NettyClient的关键配置,最后通过测试验证了通信的正确性。总结中强调了Netty在通信框架中的实用性。
摘要由CSDN通过智能技术生成

使用Java搭建一个简单的Netty通信例子

看过dubbo源码的同学应该都清楚,使用dubbo协议的底层通信是使用的netty进行交互,而最近看了dubbo的Netty部分后,自己写了个简单的Netty通信例子。

准备

工程截图

image

模块详解

  • rpc-common

    rpc-common作为各个模块都需使用的模块,工程中出现的是一些通信时请求的参数以及返回的参数,还有一些序列化的工具。

  • rpc-client

    rpc-client中目前只是单单的一个NettyClient启动类。

  • rpc-server

    rpc-client中目前也只是单单的一个NettyServer服务启动类。

需要的依赖

目前所有的依赖项都出现在 rpc-common 下的 pom.xml中。

<dependencies>
    <!-- Netty -->
    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-all</artifactId>
        <version>4.1.10.Final</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.25</version>
    </dependency>

    <!-- Protostuff -->
    <dependency>
        <groupId>com.dyuproject.protostuff</groupId>
        <artifactId>protostuff-core</artifactId>
        <version>1.0.9</version>
    </dependency>

    <dependency>
        <groupId>com.dyuproject.protostuff</groupId>
        <artifactId>protostuff-runtime</artifactId>
        <version>1.0.9</version>
    </dependency>

    <!-- Objenesis -->
    <dependency>
        <groupId>org.objenesis</groupId>
        <artifactId>objenesis</artifactId>
        <version>2.1</version>
    </dependency>

    <!-- fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.38</version>
    </dependency>
</dependencies></pre>

实现

首先我们在common中先定义本次的Request和Response的基类对象。

public class Request {

    private String requestId;

  
Java Netty 是一款高性能、异步事件驱动的网络框架,主要设计用于简化网络服务器和客户端的编程,并且能够处理高并发连接。它基于 NIO(非阻塞 I/O)技术,利用多路复用(例如 Selector)实现了对单个线程高效地管理大量并发连接的能力。Netty 框架提供了一系列高级功能,包括缓冲区管理和协议编码/解码(Codec),使得开发者可以专注于业务逻辑而无需过多关注底层网络细节。 ### Java Netty 实现 TCP 通信的基本步骤: #### 1. **构建项目** - 创建一个新的 Java 项目,在 Maven 或 Gradle 中添加相应的依赖库 `netty-all` 和 `netty-tcnative-full`。 #### 2. **配置服务端** - 定义一个服务端 `ServerBootstrap` 类型的对象,用于初始化服务端实例并绑定到特定的 IP 地址和端口。 - 使用 `ChannelPipelineFactory` 配置管道,这通常包含了接收数据、处理数据以及发送响应的过程。 - 设置必要的处理器,如 `ServerSocketChannelHandler` 负责接收新连接请求,然后创建新的 `Channel` 对象。 - 启动服务端,监听指定端口并开始接受连接。 ```java public class MyServer { public static void main(String[] args) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); // 添加你的处理器链在这里,比如定义的自定义编码器Decoder和解码器Encoder等 p.addLast(new YourCustomDecoder()); p.addLast(new YourCustomEncoder()); p.addLast("handler", new MyServerHandler()); } }) .option(ChannelOption.SO_BACKLOG, 100) .childOption(ChannelOption.SO_KEEPALIVE, true); b.bind(8080).sync().channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); } } } ``` #### 3. **配置客户端** - 定义一个客户端类,使用 `ClientBootstrap` 初始化客户端实例。 - 设置 `ChannelFutureListener` 来处理连接状态的变化。 - 发送数据到服务器并读取服务器返回的数据。 ```java public class MyClient { private final String host; private final int port; public MyClient(String host, int port) { this.host = host; this.port = port; } public void connect() throws Exception { EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ClientBootstrap b = new ClientBootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); // 添加你的处理器链,比如定义的自定义编码器Decoder和解码器Encoder等 p.addLast(new YourCustomDecoder()); p.addLast(new YourCustomEncoder()); p.addLast("handler", new MyClientHandler()); } }); SocketAddress remoteAddress = new InetSocketAddress(host, port); ChannelFuture f = b.connect(remoteAddress); f.syncUninterruptibly(); // 等待连接完成 // 如果需要,从这里开始发送数据和接收响应的操作 } finally { workerGroup.shutdownGracefully(); } } } ``` #### 4. **处理数据和异常** - 编写自定义的编码器和解码器,以及处理异常的逻辑。 ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值