@ServerEndpoint(value = "/webSocket", configurator = NutWsConfigurator.class)
@IocBean
public class WebsocketUtil extends AbstractWsEndpoint {
@Inject
private TPmPopupMessageLogic tPmPopupMessageLogic;
@Inject
private NutDao nutDao;
@Override
public WsHandler createHandler(Session session, EndpointConfig config) {
return new MyWsHandler();
}
@Override
public void onOpen(Session session, EndpointConfig config) {
MyWsHandler myWsHandler = (MyWsHandler)createHandler(session,config);
myWsHandler.setNutDao(nutDao);
myWsHandler.settPmPopupMessageLogic(tPmPopupMessageLogic);
super.onOpen(session, config);
}
}
在下面代码中调用sendJson
public void popup(HttpServletRequest req,List<User> users) throws Exception {
try {
Cnd cnd = Cnd.NEW();
cnd.desc("pm.CREATEDATE");
cnd.and("pmu.IS_READ","=",0);
Sql sql = Sqls.queryRecord("select pm.ID,pm.EMP_NAME,pm.MESSAGE,TO_CHAR(pm.CREATEDATE,'YYYY-MM-DD') as CREATEDATE,pm.TYPE,pmu.USER_ID,u.LOGIN_NAME,pmu.IS_SEND,pmu.ID AS PMUID from T_PM_POPUP_MESSAGE pm left join T_PM_POPUP_MESSAGE_USER pmu ON pm.id = pmu.POPUP_ID left join SYS_USER u on u.USER_ID = pmu.USER_ID $condition");
sql.setCondition(cnd);
nutDao.execute(sql);
List<Record> list = sql.getList(Record.class);
HttpSession session = req.getSession();
List<TPmPopupMessageUser> tPmPopupMessageUsers = new ArrayList<>();
for (User user : users) {
String wsId = (String) session.getAttribute(user.getLogin_name());
if (wsId != null) {
WebsocketUtil websocketUtil = new WebsocketUtil();
List<Record> popupData = new ArrayList<>();
int isSend = 0;
for (Record record : list) {
if (user.getUser_id().equals(record.getString("user_id"))) {
if (record.getInt("is_send") == 0) {
isSend = 1;
}
popupData.add(record);
}
TPmPopupMessageUser tPmPopupMessageUser = new TPmPopupMessageUser();
tPmPopupMessageUser.setIs_send(1);
tPmPopupMessageUser.setId(record.getString("pmuid"));
tPmPopupMessageUsers.add(tPmPopupMessageUser);
}
String message;
if (isSend == 1 && popupData.size() > 0) {
message = JSONArray.fromObject(popupData).toString();
} else {
message = "";
}
session.setAttribute("popupMessage",popupData);
websocketUtil.sendJson(wsId,message);
}
}
nutDao.updateIgnoreNull(tPmPopupMessageUsers);
logService.saveLog(req,"弹窗推送","推送","弹窗推送成功");
} catch (Exception e) {
logService.saveLog(req,"弹窗推送","推送","弹窗推送失败");
throw e;
}
}
一直发送不成功,前端onmessage回调没有触发,debugger发现
public abstract class AbstractWsEndpoint extends Endpoint {
protected ConcurrentHashMap<String, WsHandler> handlers = new ConcurrentHashMap();
protected ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap();
public Session getSession(String wsid, boolean opened) {
Session session = (Session)this.sessions.get(wsid);
if (session == null) {
return null;
} else {
return opened && !session.isOpen() ? null : session;
}
}
}
上边这边的代码中sessions为空,导致我通过sessionid获取session是,一直为null,无法发送数据