后端进度条 WebScoket 实现

90 阅读1分钟

1、 定义进度条DTO

@Data
public class ProcessBarDto {

    /**
     * 当前处理进度
     */
    private Double percent;


    /**
     * 进度最大值
     * max – the max value of the progress bar
     */
    private Double max;


    /**
     * 进度条最小值
     * min – the min value of the progress bar
     */
    private Double min;

    /**
     * 进度条颜色
     */
    private String bgColor;


    /**
     * 进度条 单位
     */
    private String unit;

    /**
     * 进度条是否可拖拽
     */
    private Boolean isDrag;


    /**
     * 进度条提示语
     */
    private String processBarMsg;

    /**
     * 进度条唯一id
     */
    private String robotNo;
}

2、 建立连接 创建会话ID (RobotNO)

 
@Component
@Slf4j
@ServerEndpoint(value = "/WSServer/{robotNo}",
        encoders = {MessageEncoder.class},
        decoders = {MessageDecoder.class})
public class WebSocketServer implements IWebSocketServer {

        @OnOpen
        public void onOpen(Session session, @PathParam("robotNo") String robotNo) {
            this.robotNo = robotNo;
            this.session = session;

            if (webSocketMap.containsKey(robotNo)) {
                webSocketMap.remove(robotNo);
                webSocketMap.put(robotNo, this);
            } else {
                webSocketMap.put(robotNo, this);
            }
         }
 
 }

3、 后端处理,向会话ID(推送处理进度)

progressBar.progressBarSendMsg(processBar,robotNo );

4、 前端监听会话消息展示进度条内容

 
@Component
@Slf4j
@ServerEndpoint(value = "/WSServer/{robotNo}",
        encoders = {MessageEncoder.class},
        decoders = {MessageDecoder.class})
public class WebSocketServer implements IWebSocketServer {

@OnMessage(maxMessageSize = 3000000)
public void onMessage(WebSocketMsgDto message, Session session) {
    long start = System.currentTimeMillis();
    log.info("客户端:" + robotNo + ",报文:" + GsonUtil.gson.toJson(message));
    try {
        if (message == null) {
            throw new RuntimeException("消息为空");
        }

    } catch (Exception e) {
        e.printStackTrace();
  
    } 
 
 }