Netty实现长连接,客户端随时发送消息给服务端,可在任意代码位置发送消息给服务端

本文介绍如何使用Netty实现客户端与服务器之间的长连接及心跳机制,并通过用户ID发送消息到服务端。涵盖Netty服务端与客户端的搭建过程,包括依赖配置、代码解析及客户端消息发送示例。

目录

pom依赖

netty服务端代码

netty客户端

PosttingObject封装netty客户端连接信息

测试客户端发送消息到服务器端


1. 可以实现socket长连接,心跳机制每隔N秒客户端给服务器发送一条消息,代表客户端还存活。

2. 可以实现在随意代码位置按照用户id标识,发送消息给服务端。


pom依赖

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

netty服务端代码

package com.kc.monitor.core.utils.netty;
 
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
 
public class NettyServer {
 
    /**
     * netty启动端口号
     */
    private static int port = 8080;
 
    public static void main(String[] args) {
        /**
         *  客户端创建两个线程池组分别为 boss线程组和工作线程组
         */
        // 用于接受客户端连接的请求 (并没有处理请求)
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        // 用于处理客户端连接的读写操作
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        // 用于创建我们的ServerBootstrap
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // LineBasedFrameDecoder解决粘包-解包问题,设置我们分割最大长度为1024
                        // 原理就是自动帮我们把带有\n或\r\n的数据进行换行
                        //socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
                        socketChannel.pipeline().addLast(new StringEncoder());// String编码器
                        socketChannel.pipeline().addLast(new StringDecoder());// String解码器
                        socketChannel.pipeline().addLast(new ServerHandler());// 管道类-接收发送消息
                    }
                });
        //  绑定我们的端口号码
        try {
            // 绑定端口号,同步等待成功
            ChannelFuture future = serverBootstrap.bind(port).sync();
            System.out.println("服务器启动成功:" + port);
            // 等待服务器监听端口
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
 
        } finally {
            // 优雅的关闭连接
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
 
}
 
 
class ServerHandler extends SimpleChannelInboundHandler<String> {
 
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
        System.out.println("8080-msg:" + msg);
        // 响应内容:
        channelHandlerContext.writeAndFlush("8080\n"); // String类型加上\n会自动粘包和拆包了
    }
}

netty客户端

package com.kc.monitor.core.utils.netty;
 
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
 
import java.net.InetSocketAddress;
import java.util.concurrent.ConcurrentHashMap;

public class NettyClient {

    /** 存储用户id和netty连接关系 */
    public static ConcurrentHashMap<String, PosttingObject> concurrentHashMap = new ConcurrentHashMap();

    public ClientHandler clientHandler = new ClientHandler();

    public void initNetty(String userId, String host, int port){
        //创建nioEventLoopGroup
        NioEventLoopGroup 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 ch) throws Exception {
                        System.out.println("正在连接中...");
                        ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(clientHandler);
                    }
                });

        try {
            // 发起连接
            ChannelFuture sync = bootstrap.connect().sync();
            System.out.println("用户:"+userId + "->服务端连接成功...");

            /* // 发送消息
            sync.channel().writeAndFlush(msg);
            System.out.println("消息发送完成");
            // 关闭连接
            sync.channel().close();*/

            // 异步等待关闭连接channel
            // sync.channel().closeFuture().sync();
            // System.out.println("连接已关闭..");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //group.shutdownGracefully();
            //System.out.println("优雅关闭连接");
        }

        PosttingObject posttingObject = new PosttingObject();
        posttingObject.setNioEventLoopGroup(group);
        posttingObject.setNettyClient(this);
        concurrentHashMap.put(userId, posttingObject);
    }

}
 
 
class ClientHandler extends SimpleChannelInboundHandler<String> {

    public ChannelHandlerContext channelHandlerContext;

    /**
     * 活跃通道可以发送消息
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channelHandlerContext = ctx;
        //channelHandlerContext.writeAndFlush("11111");
        //channelHandlerContext.channel().close();
    }
 
    /**
     * 读取消息
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
        System.out.println("接收消息:" + msg);
        //channelHandlerContext.channel().close();
    }
}

PosttingObject封装netty客户端连接信息

package com.kc.monitor.core.utils.netty;

import io.netty.channel.nio.NioEventLoopGroup;
import lombok.Data;

/**
 * @title PosttingObject 记录netty连接
 * @description
 * @author qizhentao
 * @date 2021-12-23 11:14
 */
@Data
public class PosttingObject {

    private NettyClient nettyClient;

    private NioEventLoopGroup nioEventLoopGroup;

}

测试客户端发送消息到服务器端

package com.kc.monitor.core.utils.netty;


/**
 * @title NettyClientSendMsg
 * @description
 * @author qizhentao
 * @date 2021-12-23 11:03
 */
public class NettyClientSendMsg {

    private static final String host = "192.168.52.1";
    private static final int port = 8080;

    public static void main(String[] args) {
        // 初始化Netty连接
        String userId = "1";
        new NettyClient().initNetty(userId, host, port);



        // 根据用户id发送消息到客户端
        PosttingObject posttingObject = NettyClient.concurrentHashMap.get(userId);
        try{
            // 发送消息
            NettyClient nettyClient = posttingObject.getNettyClient();
            nettyClient.clientHandler.channelHandlerContext.writeAndFlush("01\n");
            nettyClient.clientHandler.channelHandlerContext.writeAndFlush("02\n");
            nettyClient.clientHandler.channelHandlerContext.writeAndFlush("03\n");
        }finally {
            // 优雅关闭连接
            posttingObject.getNioEventLoopGroup().shutdownGracefully();
        }
    }


}

<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]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

祁_z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值