当前位置:   article > 正文

websocket使用_websocketconfigurator

websocketconfigurator

前端代码

       	  $(document).ready(function(){
       	  	var ws;
       	  	if('WebSocket' in window){  //页面初始进入就进行websocket连接
       	  	//本地调试  ws://localhost:8080/boot/webSocket
       	  	//生产地址ws://192.168.12.237:8080/boot/webSocket
       	  		ws = new WebSocket('ws://192.168.12.237:8080/boot/webSocket');
       	  	}

       	  	ws.onmessage = function(event){

       	  		var res = $.parseJSON(event.data);
       	  		var code = res.code;
       	  		if(res.code == 1){
       	  		    //调用成功
       	  		    var map = res.data;
       	  		    var status = map.status;
       	  		    $('#xIndex').val(map.xIndex);
       	  		    $('#yIndex').val(map.yIndex);
       	  		    $('#zIndex').val(map.zIndex);


       	  		}
       	  	}

       	  });       	 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

后端代码

1.增加websocket配置

package com.tqjc.system.core.config.web;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;


/**
 * @version 1.0
 * @description websocket通讯配置
 * @date 2023/3/23 9:30
 */
@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

2.websocket服务类

其中WebSocketConfigurator的作用是作为中间信使,可传递前端传过来的参数信息。如下示例,将前端客户端的IP地址传入

package com.tqjc.system.system.socket;

import com.alibaba.fastjson.JSON;

import com.tqjc.system.common.constant.GlobalConstant;
import com.tqjc.system.common.entity.bo.ResponseDataBO;
import com.tqjc.system.common.entity.bo.WebSocketMonitorBO;
import com.tqjc.system.core.config.web.WebSocketConfigurator;
import com.tqjc.system.core.threadpool.ScheduledPoolManager;
import com.tqjc.system.core.util.HttpsUtils;
import com.tqjc.system.core.util.SpringUtils;
import com.tqjc.system.system.service.SysCarInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @description TODO
 * @date 2023/3/17 11:43
 */
@ServerEndpoint(value = "/webSocket",configurator = WebSocketConfigurator.class)
@Component
@Slf4j
public class MonitorWebSocketService {



    private Map<String, WebSocketMonitorBO> sessionMap = new HashMap<>();

    /**
     * 任务前缀
     */
    private static final String taskPrefix = "MonitorWebSocketService_";





    @OnOpen
    public void onOpen(Session session) throws Exception {
        //建立连接
        log.info("MonitorWebSocketService start");
        String ip = (String) session.getUserProperties().get(GlobalConstant.STRING_IP);
        if(sessionMap.get(ip) == null){
            String taskName = new StringBuffer(taskPrefix).append(ip).toString();
            SysCarInfoService carInfoService = SpringUtils.getBean("sysCarInfoService");
            String carNo = carInfoService.getCarNo(ip);
            //todo 数据库查询对应IP的SN
            //SystemUtils.Sys_carInfo.get(ConfigConstant.CONFIG_CAR_BAK_SN);
            if(carNo == null){
                log.info("非操作天车IP:{}电脑访问",ip);
            }
            String bakSn = carInfoService.getCarBakSn(carNo);

            sessionMap.put(ip,new WebSocketMonitorBO(session,bakSn));
            ScheduledPoolManager.getInstance().scheduledExecute(new Runnable() {
                @Override
                public void run() {
                    log.debug("机器:{}执行周期性任务开始",ip);
                    //调用接口
                    double[] deftIndex = {0,0,0};

                    try {
                        //调用采数平台采数
                        double[] carLocaltionInfoForMES = HttpsUtils.getCarLocaltionInfoForMES(bakSn, carNo, deftIndex);

                        //ResponseDataBO responseDataBO = MockData();
                        //处理返回数据
                        handleResMap(carLocaltionInfoForMES,ip);
                    } catch (Exception e) {
                        log.error("周期性任务出现异常",e);
                    }
                    log.debug("机器:{}执行周期性任务结束",ip);

                }
            },0L,1L,TimeUnit.SECONDS,taskName);
        }


    }



    @OnClose
    public void onClose(Session session){
        //连接关闭
        String ip = (String) session.getUserProperties().get(GlobalConstant.STRING_IP);
        sessionMap.remove(ip);
        String taskName = new StringBuffer(taskPrefix).append(ip).toString();
        ScheduledPoolManager.getInstance().cancleTask(taskName);
        log.info("MonitorWebSocketService end");

    }




    @OnError
    public void onError(Throwable error,Session session){
        //连接关闭
        String ip = (String) session.getUserProperties().get(GlobalConstant.STRING_IP);
        //todo 异常情况处理
        log.error("MonitorWebSocketService running error");
        sendMessage(buildMessage(null,"出现异常,请联系管理员",GlobalConstant.HTTPSTATUS_ERROR),ip);
        sessionMap.remove(ip);
        error.printStackTrace();
    }




    public void sendMessage(Map resMap,String ip) {
        try {
            WebSocketMonitorBO webSocketMonitorBO = sessionMap.get(ip);

//拿到客户端的session后即可发信息            webSocketMonitorBO.getSession().getBasicRemote().sendText(JSON.toJSONString(resMap));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134

3.WebSocketConfigurator中间信使器

package com.tqjc.system.core.config.web;

import com.tqjc.system.common.constant.GlobalConstant;
import com.tqjc.system.core.util.RequestUtil;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.Map;

/**
 * @version 1.0
 * @description websocket配置
 * @date 2023/3/23 10:50
 */
public class WebSocketConfigurator extends ServerEndpointConfig.Configurator {

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        Map<String, Object> userProperties = sec.getUserProperties();
        HttpServletRequest httpServletRequest = RequestUtil.getRequest();
        if(httpServletRequest != null){
            userProperties.put(GlobalConstant.STRING_IP,httpServletRequest.getRemoteHost());
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号