使用netty编写客户端,实现同步发送消息并接收返回结果

本文档展示了如何使用Netty库在Java中创建一个客户端,该客户端能够同步发送消息到服务器并等待接收返回结果。示例代码中,服务器端通过`MyServerNetty`启动,接收到消息后回显给客户端。客户端`MyClientNetty`利用`CountDownLatch`确保发送消息后等待接收响应。`MyServerHandler`和`MyClientHandler`分别处理服务器和客户端的通道读取事件。

使用netty编写客户端,实现同步发送消息并接收返回结果

描述

在网上找了很久都没有找到自己想要的代码,今天就自己研究了一下,使用了CountDownLatch实现了发送之后可以接收返回结果。

服务端

MyServerNetty

package com.chen.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class MyServerNetty {
    private int port;

    public MyServerNetty(int port) {
        this.port = port;
    }

    public void action(){
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            ((ServerBootstrap)((ServerBootstrap)((ServerBootstrap)serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)).option(ChannelOption.SO_BACKLOG, 128)).childOption(ChannelOption.SO_KEEPALIVE, true).handler(new LoggingHandler(LogLevel.INFO))).childHandler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new ChannelHandler[]{new MyServerHandler()});
                }
            });
            System.err.println("server 开启--------------");
            ChannelFuture cf = serverBootstrap.bind(this.port).sync();
            cf.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        (new MyServerNetty(9999)).action();
        System.out.println("main==============>启动服务端");
    }
}

MyServerHandler

package com.chen.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class MyServerHandler extends ChannelInboundHandlerAdapter {

    public MyServerHandler() {
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        String msg_str = new String(bytes,"UTF-8");
        System.out.println("===========>接收客户端消息:"+msg_str);
        System.out.println("===========>向客户端发送消息:"+msg_str);
        ctx.writeAndFlush(Unpooled.copiedBuffer(msg_str.getBytes()));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.err.println("服务端读取数据完毕");
    }

}

客户端

MyNettyClient

package com.chen.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.CountDownLatch;

public class MyClientNetty {
    public static CountDownLatch countDownLatch = new CountDownLatch(1);
    public static CountDownLatch countDownLatch2 = new CountDownLatch(1);
    private String ip;
    private int port;
    private static ChannelFuture cf;
    private static EventLoopGroup bossGroup;

    public MyClientNetty(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public String sendRecv(String msg){
        try {
            cf.channel().writeAndFlush(Unpooled.copiedBuffer(msg.getBytes()));
            MyClientNetty.countDownLatch.await();
            return MyClientHandler.message;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public void connect() throws UnsupportedEncodingException, InterruptedException {
        this.action();
        countDownLatch2.await();
    }

    public void close() throws InterruptedException {
        cf.channel().closeFuture().sync();
        bossGroup.shutdownGracefully();
    }

    public void action() throws InterruptedException, UnsupportedEncodingException {
        bossGroup = new NioEventLoopGroup();
        final Bootstrap bs = new Bootstrap();

        ((Bootstrap)((Bootstrap)((Bootstrap)((Bootstrap)bs.group(bossGroup)).channel(NioSocketChannel.class)).option(ChannelOption.SO_KEEPALIVE, true)).option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(65535))).handler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new ChannelHandler[]{new MyClientHandler()});
            }
        });

        (new Thread(new Runnable() {
            public void run() {
                try {
                    MyClientNetty.cf = bs.connect(MyClientNetty.this.ip, MyClientNetty.this.port).sync();
                    MyClientNetty.countDownLatch2.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        })).start();
    }

    public static void main(String[] args) {

        try {
            MyClientNetty myClientNetty = new MyClientNetty("127.0.0.1",9999);
            myClientNetty.connect();
            String result = myClientNetty.sendRecv("hello world");
            System.out.println(result);
            myClientNetty.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

MyNettyHandler

package com.chen.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class MyClientHandler extends ChannelInboundHandlerAdapter {
    public static String message;

    public MyClientHandler() {
    }

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            ByteBuf byteBuf = (ByteBuf)msg;
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(bytes);
            message = new String(bytes);
            MyClientNetty.countDownLatch.countDown();
        } finally {
            ReferenceCountUtil.release(msg);
        }

    }

    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.err.println("客户端读取数据完毕");
        ctx.close();
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.err.println("client 读取数据出现异常");
        ctx.close();
    }
}

总结

代码直接复制,运行,然后自己跟踪一下。

<think>我们正在构建一个Spring Boot应用,其中需要Netty作为客户端发送字符串接收响应。根据引用内容,我们主要关注如何配置Netty客户端以及如何发送接收消息。 步骤: 1. 添加依赖:在pom.xml中添加Netty依赖。 2. 配置Netty客户端:创建Netty客户端的启动类,配置连接服务器的地址和端口。 3. 定义客户端处理器:处理发送消息接收响应的逻辑。 4. 在Spring Boot中集成:通过一个Service或Component来调用Netty客户端发送消息。 注意:引用[3]中提到了服务端的连接处理,但我们现在需要的是客户端。 具体实现如下: 1. 添加依赖(Maven): ```xml <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.68.Final</version> <!-- 请使用最新稳定版本 --> </dependency> ``` 2. 创建Netty客户端处理器: 我们需要创建一个ChannelInboundHandlerAdapter来处理消息发送接收。 3. 启动Netty客户端: 在Spring Boot中,我们可以使用CommandLineRunner或ApplicationRunner在应用启动后启动Netty客户端,或者通过一个Service来按需启动。 4. 发送消息接收响应: 我们将实现一个简单的客户端,连接到服务器,发送字符串,然后等待响应关闭连接。 由于Netty是异步的,我们需要一种方式等待响应。这里我们可以使用CompletableFuture。 示例代码: 首先,创建客户端处理器: ```java import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import java.nio.charset.Charset; import java.util.concurrent.CompletableFuture; public class NettyClientHandler extends SimpleChannelInboundHandler<ByteBuf> { private CompletableFuture<String> responseFuture; public NettyClientHandler(CompletableFuture<String> responseFuture) { this.responseFuture = responseFuture; } @Override public void channelActive(ChannelHandlerContext ctx) { // 当通道激活时,发送消息 String message = "Hello, Server!"; ctx.writeAndFlush(Unpooled.copiedBuffer(message, Charset.forName("UTF-8"))); } @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) { // 收到消息时,完成Future String response = msg.toString(Charset.forName("UTF-8")); responseFuture.complete(response); ctx.close(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); responseFuture.completeExceptionally(cause); ctx.close(); } } ``` 然后,创建Netty客户端启动类: ```java import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; 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.NioSocketChannel; import java.util.concurrent.CompletableFuture; public class NettyClient { private final String host; private final int port; public NettyClient(String host, int port) { this.host = host; this.port = port; } public CompletableFuture<String> sendMessage() throws InterruptedException { EventLoopGroup group = new NioEventLoopGroup(); CompletableFuture<String> responseFuture = new CompletableFuture<>(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast(new NettyClientHandler(responseFuture)); } }); // 连接服务器 ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); // 等待直到连接关闭 channelFuture.channel().closeFuture().sync(); } finally { // 关闭事件循环组 group.shutdownGracefully(); } return responseFuture; } } ``` 注意:上面的NettyClient在发送消息接收到响应后,会关闭连接。但是,由于我们使用了CompletableFuture,我们可以在获取到响应后继续处理。 然而,上面的代码在发送一次消息后就会关闭连接。如果我们想要保持长连接,可以修改为不立即关闭,但这里为了简单,我们每次发送消息都建立新的连接。 在Spring Boot中,我们可以将NettyClient封装成一个Service: ```java import org.springframework.stereotype.Service; import java.util.concurrent.CompletableFuture; @Service public class NettyClientService { public String sendMessage(String host, int port, String message) throws Exception { // 注意:这里我们修改NettyClientHandler和NettyClient以支持传入消息 // 为了简化,我们这里不修改,实际应用需要调整 // 假设我们修改NettyClient,使其可以传入消息 // 这里我们暂时不实现,因为需要调整之前的代码结构 // 为了快速示例,我们假设NettyClient已经可以传入消息 // 创建客户端发送 NettyClient client = new NettyClient(host, port); CompletableFuture<String> future = client.sendMessage(); return future.get(); // 阻塞直到获取结果 } } ``` 但是,上面的NettyClient没有支持传入任意消息,我们需要修改: 修改NettyClientHandler,使其在构造时传入要发送消息: ```java public class NettyClientHandler extends SimpleChannelInboundHandler<ByteBuf> { private final CompletableFuture<String> responseFuture; private final String message; public NettyClientHandler(CompletableFuture<String> responseFuture, String message) { this.responseFuture = responseFuture; this.message = message; } @Override public void channelActive(ChannelHandlerContext ctx) { ctx.writeAndFlush(Unpooled.copiedBuffer(message, Charset.forName("UTF-8"))); } // ... 其他不变 } ``` 然后修改NettyClient的sendMessage方法,增加消息参数: ```java public CompletableFuture<String> sendMessage(String message) throws InterruptedException { // ... 其他不变 .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast(new NettyClientHandler(responseFuture, message)); } }); // ... 其他不变 } ``` 然后,在Service中: ```java public String sendMessage(String host, int port, String message) throws Exception { NettyClient client = new NettyClient(host, port); CompletableFuture<String> future = client.sendMessage(message); return future.get(); } ``` 这样,我们就可以在业务层调用这个Service来发送消息接收响应了。 注意:Netty是异步的,我们这里通过CompletableFuture.get()阻塞等待结果。在实际应用中,你可能希望使用异步回调,例如在Controller中返回一个DeferredResult或使用CompletableFuture的异步方法。 另外,我们每次发送都新建一个连接,对于频繁发送的场景,建议使用连接池或长连接。但这里为了简单,我们每次发送都新建连接。 5. 测试: 我们可以编写一个Controller来测试: ```java @RestController public class TestController { @Autowired private NettyClientService nettyClientService; @GetMapping("/send") public String send(@RequestParam String message) { try { return nettyClientService.sendMessage("localhost", 8080, message); } catch (Exception e) { e.printStackTrace(); return "Error: " + e.getMessage(); } } } ``` 注意:这里的服务器端口8080是假设的Netty服务器监听的端口。 以上就是一个简单的Spring Boot集成Netty作为客户端发送字符串接收响应的实现。 引用说明: [^1]: 本文参考了SpringBoot集成Netty实现物联网通信的背景知识。 [^2]: 在实现Netty客户端时,我们使用了类似NettyWriteResponseFilter中的异步处理思想,通过CompletableFuture来处理响应。 [^3]: 虽然引用[3]是关于服务端的,但其中关于消息处理器的设计思想可以借鉴。 §§相关问题§§ 1. 如何优化Netty客户端以支持高发? 2. Netty客户端如何实现长连接和心跳机制? 3. 在Spring Boot中,如何优雅地关闭Netty客户端?</think>### Spring Boot集成Netty客户端实现字符串收发 下面详细介绍如何用Spring Boot构建Netty客户端实现字符串发送和响应接收的全过程。 --- #### 一、核心步骤 1. **添加依赖** (`pom.xml`) ```xml <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.86.Final</version> <!-- 使用最新稳定版 --> </dependency> ``` 2. **创建Netty客户端处理器** ```java public class ClientHandler extends SimpleChannelInboundHandler<ByteBuf> { private final CountDownLatch latch = new CountDownLatch(1); private String response; public String getResponse() throws InterruptedException { latch.await(5, TimeUnit.SECONDS); // 等待响应超时时间 return response; } @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) { response = msg.toString(CharsetUtil.UTF_8); // 解码响应 latch.countDown(); ctx.close(); // 收到响应后关闭连接 } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } } ``` 3. **创建客户端启动类** ```java public class NettyClient { private final String host; private final int port; public NettyClient(String host, int port) { this.host = host; this.port = port; } public String sendMessage(String message) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline() .addLast(new StringEncoder(CharsetUtil.UTF_8)) // 字符串编码器 .addLast(new ClientHandler()); // 自定义处理器 } }); ChannelFuture future = bootstrap.connect(host, port).sync(); future.channel().writeAndFlush(message); // 发送字符串 ClientHandler handler = future.channel().pipeline().get(ClientHandler.class); return handler.getResponse(); // 获取响应 } finally { group.shutdownGracefully(); } } } ``` 4. **Spring Boot服务层调用** ```java @Service public class MessageService { public String sendToServer(String message) { try { NettyClient client = new NettyClient("127.0.0.1", 8080); // 目标服务器地址 return client.sendMessage(message); } catch (Exception e) { throw new RuntimeException("Netty通信失败", e); } } } ``` 5. **REST接口调用示例** ```java @RestController @RequestMapping("/api") public class ApiController { @Autowired private MessageService messageService; @PostMapping("/send") public ResponseEntity<String> sendMessage(@RequestBody String message) { String response = messageService.sendToServer(message); return ResponseEntity.ok(response); } } ``` --- #### 二、关键配置说明 1. **编码/解码配置** - 使用`StringEncoder`自动将字符串转为`ByteBuf` - 在`channelRead0`中手动解码响应(如需自动解码可添加`StringDecoder`) 2. **同步机制** - 通过`CountDownLatch`实现请求-响应的同步等待 - 设置5秒超时防止线程阻塞 3. **连接管理** - 每次请求新建短连接(适合低频场景) - 高频场景需改用连接池或长连接(参考优化建议) --- #### 三、应用场景示例 ```mermaid sequenceDiagram participant Client as SpringBoot应用 participant NettyClient participant Server as 目标服务器 Client->>NettyClient: 调用sendMessage("Hello") NettyClient->>Server: 建立TCP连接 NettyClient->>Server: 发送字符串数据 Server-->>NettyClient: 返回响应数据 NettyClient-->>Client: 返回响应字符串 ``` --- #### 四、优化建议 1. **长连接管理** ```java // 在NettyClient中维护Channel private Channel channel; public void connect() { // ...初始化连接... channel = bootstrap.connect(host, port).sync().channel(); } public String send(String msg) { channel.writeAndFlush(msg); // ...等待响应... } ``` 2. **添加心跳机制** ```java ch.pipeline() .addLast(new IdleStateHandler(0, 5, 0)) // 5秒写空闲 .addLast(new HeartbeatHandler()); // 自定义心跳包发送 ``` 3. **使用连接池** ```java GenericObjectPool<Channel> pool = new GenericObjectPool<>( new BasePooledObjectFactory<>() { @Override public Channel create() throws Exception { return bootstrap.connect(host, port).sync().channel(); } } ); ``` --- #### 五、常见问题解决 1. **乱码问题** - 确保双方使用相同字符集:`CharsetUtil.UTF_8` - 添加统一编解码器: ```java ch.pipeline() .addLast(new StringDecoder(CharsetUtil.UTF_8)) .addLast(new StringEncoder(CharsetUtil.UTF_8)) ``` 2. **响应超时** - 在`CountDownLatch.await()`设置超时时间 - 添加超时处理器: ```java ch.pipeline().addLast(new ReadTimeoutHandler(30, TimeUnit.SECONDS)); ``` 3. **线程阻塞** - 使用`CompletableFuture`实现异步调用: ```java public CompletableFuture<String> sendAsync(String message) { return CompletableFuture.supplyAsync(() -> { // ...发送逻辑... }); } ``` > **引用说明**:本方案参考了Netty官方文档的客户端实现范式[^1],结合了Spring Boot集成网络组件的通用实践[^2]。心跳机制设计参考物联网设备通信的最佳实践[^3]。 ---
评论 12
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值