SpringBoot+Neety+Vue实现心跳监测功能

一、项目介绍

本项目是基于SpringBoot、Netty和Vue实现的心跳监测系统。通过Netty实现服务器和客户端之间的通信,客户端定时发送心跳包给服务器,服务器接收到心跳包后会进行相应的处理。通过Vue实现前端页面展示服务器和客户端的连接状态。

二、实现过程

  1. 项目搭建
    首先,我们需要创建一个SpringBoot项目,引入相关依赖,包括SpringBoot、Netty和Vue等。

  2. 编写服务器代码
    创建一个Netty服务器类,实现服务器的启动和客户端连接的处理。在服务器类中,我们需要实现以下几个方法:

  • 启动服务器:创建一个EventLoopGroup来接收和处理客户端连接,并设置相关参数,如端口号等。
  • 客户端连接处理:在连接建立时,将连接加入到连接池中并分配一个唯一的ID,同时发送心跳请求给客户端。
  • 心跳请求处理:接收到客户端发送的心跳请求后进行相应处理,如更新连接的最后一次心跳时间等。
  • 心跳包发送:在规定的时间内,向连接池中的所有连接发送心跳请求,更新连接状态。
  1. 编写客户端代码
    创建一个Netty客户端类,实现客户端的连接和与服务器的通信。在客户端类中,我们需要实现以下几个方法:
  • 连接服务器:创建一个Bootstrap类,设置相关参数,如服务器地址和端口号。
  • 心跳请求发送:定时发送心跳请求给服务器。
  • 心跳请求处理:接收到服务器发送的心跳请求后进行相应处理,如更新最后一次心跳时间等。
  1. 编写前端页面
    使用Vue框架来实现前端页面的展示。在前端页面中,我们需要实现以下几个功能:
  • 实时显示服务器和客户端的连接状态。
  • 实时显示连接的最后一次心跳时间。
  • 实时显示连接的数目。
  1. 启动项目
    首先启动服务器,然后启动多个客户端,通过前端页面可以实时显示客户端的连接状态和心跳时间等。

三、代码示例

  1. 服务器代码示例
@Component
public class NettyServer {
    
    

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    // 启动服务器
    public void startServer(int port) throws Exception {
    
    
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();

        try {
    
    
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
    
    
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
    
    
                            ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                            ch.pipeline().addLast(new ObjectEncoder());
                            ch.pipeline().addLast(new ServerHandler());
                        }
                    });

            ChannelFuture future = bootstrap.bind(port).sync();
            System.out.println("Server started at port " + port);

            future.channel().closeFuture().sync();
        } finally {
    
    
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    // 客户端连接处理
    public static void handleConnection(ChannelHandlerContext ctx) {
    
    
        String clientId = UUID.randomUUID().toString();
        Channel channel = ctx.channel();

        // 将连接加入到连接池中并分配一个唯一的ID
        ConnectionPool.addConnection(clientId, channel);

        // 发送心跳请求给客户端
        HeartbeatRequest request = new HeartbeatRequest(clientId, new Date());
        channel.writeAndFlush(request);

        System.out.println("Client connected: " + clientId);
    }

    // 心跳请求处理
    public static void handleHeartbeatRequest(ChannelHandlerContext ctx, HeartbeatRequest request) {
    
    
        String clientId = request.getClientId();

        // 更新连接的最后一次心跳时间
        ConnectionPool.updateLastHeartbeatTime(clientId, new Date());

        // 发送心跳请求给客户端
        HeartbeatRequest heartbeat = new HeartbeatRequest(clientId, new Date());
        ctx.channel().writeAndFlush(heartbeat);
    }

    // 心跳包发送
    public static void sendHeartbeatRequest() {
    
    
        List<Channel> channels = ConnectionPool.getAllConnections();

        for (Channel channel : channels) {
    
    
            String clientId = ConnectionPool.getConnectionId(channel);

            // 发送心跳请求给客户端
            HeartbeatRequest request = new HeartbeatRequest(clientId, new Date());
            channel.writeAndFlush(request);
        }
    }
}
  1. 客户端代码示例
@Component
public class NettyClient {
    
    

    private EventLoopGroup group;

    @PostConstruct
    public void startClient() {
    
    
        group = new NioEventLoopGroup();

        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) throws Exception {
    
    
                            ch.pipeline().addLast(new ObjectEncoder());
                            ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                            ch.pipeline().addLast(new ClientHandler());
                        }
                    });

            ChannelFuture future = bootstrap.connect("localhost", 8888).sync();
            future.channel().closeFuture().sync();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            group.shutdownGracefully();
        }
    }

    // 心跳请求发送
    public static void sendHeartbeatRequest(Channel channel) {
    
    
        String clientId = ConnectionPool.getConnectionId(channel);

        // 发送心跳请求给服务器
        HeartbeatRequest request = new HeartbeatRequest(clientId, new Date());
        channel.writeAndFlush(request);
    }

    // 心跳请求处理
    public static void handleHeartbeatRequest(ChannelHandlerContext ctx, HeartbeatRequest request) {
    
    
        String clientId = request.getClientId();

        // 更新最后一次心跳时间
        ConnectionPool.updateLastHeartbeatTime(clientId, new Date());
    }
}
  1. 前端页面示例
<template>
  <div>
    <h1>心跳监测系统</h1>
    <h3>服务器连接状态:{
   
   { serverStatus }}</h3>
    <h3>客户端连接状态:{
   
   { clientStatus }}</h3>
    <h3>客户端心跳时间:{
   
   { heartbeatTime }}</h3>
    <h3>连接数:{
   
   { connectionCount }}</h3>
  </div>
</template>

<script>
export default {
      
      
  data() {
      
      
    return {
      
      
      serverStatus: '未连接',
      clientStatus: '未连接',
      heartbeatTime: '',
      connectionCount: 0,
    };
  },
  mounted() {
      
      
    // 建立WebSocket连接
    const socket = new WebSocket('ws://localhost:8888/ws');

    // 监听连接状态变化
    socket.onopen = () => {
      
      
      this.serverStatus = '已连接';
    };

    // 监听接收到消息
    socket.onmessage = (event) => {
      
      
      const data = JSON.parse(event.data);
      if (data.type === 'clientStatus') {
      
      
        this.clientStatus = data.message;
      } else if (data.type === 'heartbeatTime') {
      
      
        this.heartbeatTime = data.message;
      } else if (data.type === 'connectionCount') {
      
      
        this.connectionCount = data.message;
      }
    };

    // 监听连接关闭
    socket.onclose = () => {
      
      
      this.serverStatus = '已关闭';
    };
  },
};
</script>

总结:

本项目通过Netty实现了服务器与客户端之间的通信,通过发送心跳请求来监测客户端的连接状态。通过Vue实现了前端页面来展示服务器和客户端的连接状态、心跳时间和连接数。通过以上代码示例,可以详细了解到实现过程和具体的代码。

猜你喜欢

转载自blog.csdn.net/IT_WEH_coder/article/details/141791766