将Netty连接客户端和断开重连的处理抽离到连接工具类,方便调用:
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;
/**
*
* @Desc:客户端连接工具类
* @create: 2025-10-03 10:51
**/
@Configuration
@Slf4j
public class ConnectUtils {
@Value("${netty.server.host}")
private String host;
@Value("${netty.server.port}")
private int port;
private NioEventLoopGroup eventLoopGroup;
private Channel channel;
/**
* 启动Netty服务器
*/
public void connect() {
eventLoopGroup = new NioEventLoopGroup();
// 创建客户端引导器Bootstrap,用于完成Netty整个程序的组件初始化,启动,服务器连接
Bootstrap serverBootstrap = new Bootstrap();
//设置数据包边界,解决粘包半包问题
ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
serverBootstrap.group(eventLoopGroup)
// 设置ServerSocketCh

最低0.47元/天 解锁文章
213

被折叠的 条评论
为什么被折叠?



