websocket 使用实例

package com.yonyou.mes.dashboard.device.web;

import java.io.IOException;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.server.standard.SpringConfigurator;

import com.yonyou.mes.dashboard.core.device.service.DeviceWSService;

/**
* @description 生产管理
*/
@ServerEndpoint(value = "/dashboard/ws/device/{userId}", configurator = SpringConfigurator.class)
public class DeviceWSController {

@Autowired
DeviceWSService devWSService;

/**
* @Description websocket建立连接
* @param userId
* 用户id
* @param period
* 请求的刷新频率
* @param session
* websocket连接的session属性
* @throws IOException
* @CreateTime 2018年8月29日
*/
@OnOpen
public void onOpen(@PathParam("userId") String userId, Session session)
throws IOException {
devWSService.openHandler(userId, session);
}

/**
* @Description websocket关闭连接
* @param userId
* 终端
* @param session
* @CreateTime 2018年8月29日
*/
@OnClose
public void onClose(@PathParam("userId") String userId, Session session) {
devWSService.closeHandler(userId, session);
}

/**
* @Description websocket接收消息
* @param userId
* @param message
* @param session
* @Creator zhangdengke
* @CreateTime 2018年8月29日
*/
@OnMessage
public void onMessage(@PathParam("userId") String userId, String message,
Session session) {
devWSService.messageHandler(userId, message, session);
}

/**
* @Description websocket连接报错
* @param userId
* @param session
* @param error
* @CreateTime 2018年8月29日
*/
@OnError
public void onError(@PathParam("userId") String userId, Session session,
Throwable error) {
devWSService.errorHandler(userId, session, error);
}

}

 

 

package com.yonyou.mes.dashboard.core.device.service;

import javax.websocket.Session;
import javax.websocket.server.PathParam;

public interface DeviceWSService {
public void openHandler(@PathParam("userId") String userId, Session session);

public void closeHandler(@PathParam("userId") String userId, Session session);

public void messageHandler(@PathParam("userId") String userId,
String message, Session session);

public void errorHandler(@PathParam("userId") String userId,
Session session, Throwable error);

}

 

package com.yonyou.mes.dashboard.core.device.serviceimpl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.websocket.Session;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.yonyou.me.utils.dto.ExceptionResult;
import com.yonyou.me.utils.dto.Result;
import com.yonyou.me.utils.dto.ResultError;
import com.yonyou.me.utils.exception.ExceptionUtils;
import com.yonyou.mes.dashboard.core.common.utils.excelutil.ExcelConst;
import com.yonyou.mes.dashboard.core.common.utils.excelutil.ExcelUtil;
import com.yonyou.mes.dashboard.core.device.entity.CheckVO;
import com.yonyou.mes.dashboard.core.device.entity.EvaluateBodyVO;
import com.yonyou.mes.dashboard.core.device.entity.EvaluateHeadVO;
import com.yonyou.mes.dashboard.core.device.entity.ProcessVO;
import com.yonyou.mes.dashboard.core.device.entity.RepairCostVO;
import com.yonyou.mes.dashboard.core.device.entity.RepairVO;
import com.yonyou.mes.dashboard.core.prodmanage.service.ProdmanageWSService;

@Service
public class DeviceWSServiceImpl implements ProdmanageWSService{

private Logger logger = LoggerFactory
.getLogger(DeviceWSServiceImpl.class);

// 每个终端的连接数(1对n)
private static Map<String, Set<Session>> userSessions = new HashMap<>();

@Override
public void openHandler(String userId, Session session) {
logger.info("websocket connected!");
// 判断用户是不是第一次登录,维护每个用户的会话
if (userSessions.containsKey(userId)) {
userSessions.get(userId).add(session);
} else {
Set<Session> _session = new HashSet<Session>();
_session.add(session);
userSessions.put(userId, _session);
}

}

@Override
public void closeHandler(String userId, Session session) {
// 判断用户是否所有终端会话都结束了
if (userSessions.get(userId) == null
|| userSessions.get(userId).size() == 0) {
return;
} else if (userSessions.get(userId).size() == 1) {
userSessions.remove(userId);
} else {
userSessions.get(userId).remove(session);
}

}

@Override
public void messageHandler(String userId, String message, Session session) {
if (session == null) {
logger.info("session null");
} else {
logger.info("websocket is sending message!");
this.sendToAllTerminal(session, userId, message);
}

}

@Override
public void errorHandler(String userId, Session session, Throwable error) {
new Throwable().printStackTrace();

}

private void sendToAllTerminal(Session session, String userId,
String message) {
if (StringUtils.isEmpty(userId)) {
ExceptionUtils.wrapBusinessException("未知终端请求,不予返回!");
} else if (StringUtils.isEmpty(message)) {
ExceptionUtils.wrapBusinessException("请求不明确,请指明module,暂不予返回!");
} else {
try {
// 对请求进行解构,warehouse-料库动态,stockbin-料仓动态
JSONObject reqObj = JSONObject.fromObject(message);
JSONObject searchParam = reqObj.getJSONObject("searchParams");
String reqModule = searchParam.getString("module");
// 根据不同请求,执行不同操作
switch (reqModule) {
case "process": //设备主流程
session.getBasicRemote().sendText(getProcessInfo().toString());
break;
case "repair": //今日检修
session.getBasicRemote().sendText(getRepairInfo().toString());
break;
case "check": //今日点检
session.getBasicRemote().sendText(getCheckInfo().toString());
break;
case "repairCost": //检修费用统计
session.getBasicRemote().sendText(getRepairCostInfo().toString());
break;
case "evaluate": //生产指标体系平价
session.getBasicRemote().sendText(getEvaluateInfo().toString());
break;

default:
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 获取产品进度百分比
* @return
* 2018年8月29日
*/
private JSONObject getProcessInfo() {
Result result = new Result();
//查询数据类型为产量类的全年数量
try {
List<ProcessVO> headList = ExcelUtil.importExcelDataToList(this
.getClass().getClassLoader().getResource("/").getPath()
+ ExcelConst.DEVICE_DATA, 0, ProcessVO.class);
if (headList!=null && headList.size()>0) {
JSONArray bodyJson = JSONArray.parseArray(JSON
.toJSONString(headList));
Map<String, Object> data = new HashMap<String, Object>();
data.put("data", bodyJson);
result.setData(data);
}else {
result.setData(null);
ResultError resultError = new ResultError();
resultError.setMessage("无数据!");
result.setMessage(resultError);
result.setSuccess(true);
}
} catch (Exception ex) {
result = ExceptionResult.process(ex);
}
JSONObject rtnObj = JSONObject.fromObject(result);
return rtnObj;
}

/**
* 今日检修
* @return
* 2018年8月31日
*/
private JSONObject getRepairInfo() {
Result result = new Result();
//查询数据类型为产量类的全年数量
try {
List<RepairVO> headList = ExcelUtil.importExcelDataToList(this
.getClass().getClassLoader().getResource("/").getPath()
+ ExcelConst.DEVICE_DATA, 1, RepairVO.class);
if (headList!=null && headList.size()>0) {
JSONArray bodyJson = JSONArray.parseArray(JSON
.toJSONString(headList));
Map<String, Object> data = new HashMap<String, Object>();
data.put("data", bodyJson);
result.setData(data);
}else {
result.setData(null);
ResultError resultError = new ResultError();
resultError.setMessage("无数据!");
result.setMessage(resultError);
result.setSuccess(true);
}

} catch (Exception ex) {
result = ExceptionResult.process(ex);
}
JSONObject rtnObj = JSONObject.fromObject(result);
return rtnObj;
}


/**
* 今日点检
* @return
* 2018年8月29日
*/
private JSONObject getCheckInfo() {
Result result = new Result();
try {
List<CheckVO> headList = ExcelUtil.importExcelDataToList(this
.getClass().getClassLoader().getResource("/").getPath()
+ ExcelConst.DEVICE_DATA, 2, CheckVO.class);
if (headList!=null && headList.size()>0) {
JSONArray bodyJson = JSONArray.parseArray(JSON
.toJSONString(headList));
Map<String, Object> data = new HashMap<String, Object>();
data.put("data", bodyJson);
result.setData(data);
}else {
result.setData(null);
ResultError resultError = new ResultError();
resultError.setMessage("无数据!");
result.setMessage(resultError);
result.setSuccess(true);
}

} catch (Exception ex) {
result = ExceptionResult.process(ex);
}
JSONObject rtnObj = JSONObject.fromObject(result);
return rtnObj;
}




/**
* 检修费用统计
* @return
* 2018年8月29日
*/
private JSONObject getRepairCostInfo() {
Result result = new Result();
try {
List<RepairCostVO> headList = ExcelUtil.importExcelDataToList(this
.getClass().getClassLoader().getResource("/").getPath()
+ ExcelConst.DEVICE_DATA, 3, RepairCostVO.class);
if (headList!=null && headList.size()>0) {
JSONArray bodyJson = JSONArray.parseArray(JSON
.toJSONString(headList));
Map<String, Object> data = new HashMap<String, Object>();
data.put("data", bodyJson);
result.setData(data);
}else {
result.setData(null);
ResultError resultError = new ResultError();
resultError.setMessage("无数据!");
result.setMessage(resultError);
result.setSuccess(true);
}
} catch (Exception ex) {
result = ExceptionResult.process(ex);
}
JSONObject rtnObj = JSONObject.fromObject(result);
return rtnObj;
}



/**
* 获取生产指标体系平价
* @return
* 2018年8月29日
*/
private JSONObject getEvaluateInfo() {
Result result = new Result();
try {
List<EvaluateHeadVO> headList = ExcelUtil.importExcelDataToList(this
.getClass().getClassLoader().getResource("/").getPath()
+ ExcelConst.PRODMANAGE_DATA, 4, EvaluateHeadVO.class);
List<EvaluateBodyVO> bodyList = ExcelUtil.importExcelDataToList(this
.getClass().getClassLoader().getResource("/").getPath()
+ ExcelConst.PRODMANAGE_DATA, 5, EvaluateBodyVO.class);
List<Map<String, Object>> listMap = new ArrayList<Map<String,Object>>();
if (headList!=null && headList.size()>0) {
for (EvaluateHeadVO baHeadVO : headList) {
Map<String, Object> map = new HashMap<String, Object>();
List<EvaluateBodyVO> list = new ArrayList<EvaluateBodyVO>();
String id = baHeadVO.getId();
for (EvaluateBodyVO baBodyVO : bodyList) {
if (baBodyVO.getPk_evaluate().equals(id)) {
list.add(baBodyVO);
}
}
map.put("head",baHeadVO);
map.put("body", list);
listMap.add(map);
JSONArray bodyJson = JSONArray.parseArray(JSON
.toJSONString(listMap));
Map<String, Object> data = new HashMap<String, Object>();
data.put("data", bodyJson);
data.put("module", "evaluate");
result.setData(data);
}
}else {
result.setData(null);
ResultError resultError = new ResultError();
resultError.setMessage("无数据!");
result.setMessage(resultError);
result.setSuccess(true);
}

} catch (Exception ex) {
result = ExceptionResult.process(ex);
}
JSONObject rtnObj = JSONObject.fromObject(result);
return rtnObj;
}

}

posted @ 2018-09-03 11:27  天毅ha  阅读(63)  评论(0)    收藏  举报