赞
踩
$(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); } } });
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(); } }
其中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(); } } }
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()); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。