WebSocket.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. package com.izouma.meta.websocket;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.izouma.meta.config.Constants;
  5. import com.izouma.meta.domain.MetaEmail;
  6. import com.izouma.meta.domain.MetaEmailRecord;
  7. import com.izouma.meta.domain.MetaSwitch;
  8. import com.izouma.meta.dto.PublicScreenChatExceptionMsg;
  9. import com.izouma.meta.repo.MetaEmailRecordRepo;
  10. import com.izouma.meta.repo.MetaEmailRepo;
  11. import com.izouma.meta.repo.MetaSwitchRepo;
  12. import com.izouma.meta.repo.MetaZouMaLightRepo;
  13. import com.izouma.meta.utils.ApplicationContextUtil;
  14. import lombok.extern.slf4j.Slf4j;
  15. import org.apache.commons.collections.CollectionUtils;
  16. import org.apache.commons.lang.StringUtils;
  17. import org.springframework.stereotype.Service;
  18. import javax.websocket.*;
  19. import javax.websocket.server.PathParam;
  20. import javax.websocket.server.ServerEndpoint;
  21. import java.util.ArrayList;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.Objects;
  25. import java.util.concurrent.ConcurrentHashMap;
  26. @Service
  27. @ServerEndpoint(value = "/websocket/{userId}")
  28. @Slf4j
  29. public class WebSocket {
  30. /**
  31. * 当前在线的客户端map
  32. */
  33. private static final Map<String, Session> clients = new ConcurrentHashMap();
  34. private WebsocketCommon websocketCommon;
  35. private MetaEmailRepo metaEmailRepo;
  36. private MetaEmailRecordRepo metaEmailRecordRepo;
  37. private MetaZouMaLightRepo metaZouMaLightRepo;
  38. private MetaSwitchRepo metaSwitchRepo;
  39. private void init() {
  40. if (Objects.isNull(websocketCommon)) {
  41. websocketCommon = (WebsocketCommon) ApplicationContextUtil.getBean("websocketCommon");
  42. }
  43. if (Objects.isNull(metaEmailRepo)) {
  44. metaEmailRepo = (MetaEmailRepo) ApplicationContextUtil.getBean("metaEmailRepo");
  45. }
  46. if (Objects.isNull(metaEmailRecordRepo)) {
  47. metaEmailRecordRepo = (MetaEmailRecordRepo) ApplicationContextUtil.getBean("metaEmailRecordRepo");
  48. }
  49. if (Objects.isNull(metaZouMaLightRepo)) {
  50. metaZouMaLightRepo = (MetaZouMaLightRepo) ApplicationContextUtil.getBean("metaZouMaLightRepo");
  51. }
  52. if (Objects.isNull(metaSwitchRepo)) {
  53. metaSwitchRepo = (MetaSwitchRepo) ApplicationContextUtil.getBean("metaSwitchRepo");
  54. }
  55. }
  56. @OnOpen
  57. public void onOpen(@PathParam("userId") String userId, Session session) {
  58. init();
  59. // 判断当前玩家是否在其他地方登陆
  60. if (clients.containsKey(userId)) {
  61. String msg = String.format("已在别处登陆,sessionId为[%S],正在为您关闭本连接", session.getId());
  62. exceptionHandle(userId, new PublicScreenChatExceptionMsg(1, msg));
  63. try {
  64. log.info("关闭session连接");
  65. clients.get(userId).close();
  66. } catch (Exception e) {
  67. exceptionHandle(userId, new PublicScreenChatExceptionMsg(1, String.format("session close throw exception[%S]", e)));
  68. return;
  69. }
  70. }
  71. log.info("现在来连接的sessionId:" + session.getId() + "玩家id:" + userId);
  72. clients.put(userId, session);
  73. MetaSwitch metaSwitchFire = metaSwitchRepo.findByNameAndDel(Constants.META_WEBSOCKET_NOTICE_FIRE, false);
  74. if (Objects.isNull(metaSwitchFire)) {
  75. return;
  76. }
  77. if (metaSwitchFire.isStatus()) {
  78. websocketCommon.sendMessageTo(clients, JSON.toJSONString(Constants.META_WEBSOCKET_NOTICE_FIRE_OPEN), userId);
  79. }
  80. MetaSwitch metaSwitchLive = metaSwitchRepo.findByNameAndDel(Constants.META_WEBSOCKET_NOTICE_LIVE, false);
  81. if (Objects.isNull(metaSwitchLive)) {
  82. return;
  83. }
  84. if (metaSwitchLive.isStatus()) {
  85. websocketCommon.sendMessageTo(clients, JSON.toJSONString(Constants.META_WEBSOCKET_NOTICE_LIVE_OPEN), userId);
  86. }
  87. }
  88. @OnError
  89. public void onError(Session session, Throwable error) {
  90. // 异常处理
  91. error.printStackTrace();
  92. log.error(String.format("sessionId[%S]的服务端发生了错误:[%S]", session.getId(), error));
  93. }
  94. @OnClose
  95. public void onClose(@PathParam("userId") String userId, Session session) {
  96. log.info(String.format("关闭session[%S]连接", session.getId()));
  97. clients.remove(userId);
  98. }
  99. @OnMessage
  100. public void onMessage(@PathParam("userId") String userId, String message, Session session) {
  101. init();
  102. if (StringUtils.isBlank(message)) {
  103. log.error("Illegal parameter : message can not be null");
  104. return;
  105. }
  106. if (Constants.HEART_RECEIVE.equals(message)) {
  107. log.info(String.format("sessionId:[%S] userId:[%S] 连接正常", session.getId(), userId));
  108. websocketCommon.sendMessageTo(clients, Constants.HEART_RETURN, userId);
  109. return;
  110. }
  111. JSONObject jsonObject = JSON.parseObject(message);
  112. String type = jsonObject.getString("type");
  113. log.info("来自客户端消息:" + message + "客户端的id是:" + session.getId());
  114. switch (type) {
  115. case Constants.META_WEBSOCKET_NOTICE_EMAIL_NOTICE:
  116. log.info("新邮件通知");
  117. websocketCommon.sendMessageToOther(clients, Constants.META_WEBSOCKET_NOTICE_EMAIL_NOTICE, userId);
  118. break;
  119. case Constants.META_WEBSOCKET_NOTICE_EMAIL:
  120. log.info("查询邮件");
  121. try {
  122. List<MetaEmail> metaEmails = queryEmail(Long.parseLong(userId));
  123. websocketCommon.sendMessageTo(clients, CollectionUtils.isNotEmpty(metaEmails) ? JSON.toJSONString(metaEmails) : JSON.toJSONString(new ArrayList<>()), userId);
  124. } catch (Exception e) {
  125. log.error(String.format("查询邮件失败,错误信息[%S]", e.getMessage()));
  126. }
  127. break;
  128. case Constants.META_WEBSOCKET_NOTICE_EMAIL_READ:
  129. log.info("读取邮件");
  130. try {
  131. Long emailId = Long.parseLong(jsonObject.getString("value"));
  132. metaEmailRecordRepo.save(new MetaEmailRecord(Long.parseLong(userId), emailId, false, true));
  133. } catch (Exception e) {
  134. log.error(String.format("读取邮件失败,错误信息[%S]", e.getMessage()));
  135. }
  136. break;
  137. case Constants.META_WEBSOCKET_NOTICE_EMAIL_DEL:
  138. log.info("删除邮件");
  139. try {
  140. Long emailId = Long.parseLong(jsonObject.getString("value"));
  141. delEmail(Long.parseLong(userId), emailId);
  142. } catch (Exception e) {
  143. log.error(String.format("读取邮件失败,错误信息[%S]", e.getMessage()));
  144. }
  145. break;
  146. case Constants.META_WEBSOCKET_NOTICE_ZOU_MA_LIGHT_NOTICE:
  147. log.info("走马灯更新通知");
  148. websocketCommon.sendMessageToOther(clients, Constants.META_WEBSOCKET_NOTICE_ZOU_MA_LIGHT_NOTICE, userId);
  149. break;
  150. case Constants.META_WEBSOCKET_NOTICE_ZOU_MA_LIGHT:
  151. log.info("查询走马灯");
  152. String description = metaZouMaLightRepo.findDescriptionByPublishAndDel(true, false);
  153. if (StringUtils.isNotBlank(description)) {
  154. websocketCommon.sendMessageToOther(clients, description, userId);
  155. }
  156. break;
  157. case Constants.META_WEBSOCKET_NOTICE_FIRE_OPEN:
  158. log.info("烟花开启");
  159. websocketCommon.sendMessageToOther(clients, Constants.META_WEBSOCKET_NOTICE_FIRE_OPEN, userId);
  160. break;
  161. case Constants.META_WEBSOCKET_NOTICE_FIRE_CLOSE:
  162. log.info("烟花关闭");
  163. websocketCommon.sendMessageToOther(clients, Constants.META_WEBSOCKET_NOTICE_FIRE_CLOSE, userId);
  164. break;
  165. case Constants.META_WEBSOCKET_NOTICE_LIVE_OPEN:
  166. log.info("直播开启");
  167. websocketCommon.sendMessageToOther(clients, Constants.META_WEBSOCKET_NOTICE_LIVE_OPEN, userId);
  168. break;
  169. case Constants.META_WEBSOCKET_NOTICE_LIVE_CLOSE:
  170. log.info("直播关闭");
  171. websocketCommon.sendMessageToOther(clients, Constants.META_WEBSOCKET_NOTICE_LIVE_CLOSE, userId);
  172. break;
  173. default:
  174. log.error(String.format("不支持的类型[%S]", type));
  175. }
  176. }
  177. /**
  178. * 查询未删除邮件
  179. *
  180. * @param userId 用户id
  181. * @return 未删除邮件
  182. */
  183. private List<MetaEmail> queryEmail(Long userId) {
  184. init();
  185. List<Long> delIds = metaEmailRecordRepo.findEmailIdByDel(userId, true);
  186. List<MetaEmail> metaEmails;
  187. metaEmails = CollectionUtils.isEmpty(delIds) ? metaEmailRepo.findAllByPublishAndDel(true, false) : metaEmailRepo.findAllByPublishAndDelAndIdNotIn(true, false, delIds);
  188. if (CollectionUtils.isEmpty(metaEmails)) {
  189. return metaEmails;
  190. }
  191. List<Long> readIds = metaEmailRecordRepo.findEmailIdRead(userId, true);
  192. if (CollectionUtils.isEmpty(readIds)) {
  193. return metaEmails;
  194. }
  195. metaEmails.forEach(metaEmail -> {
  196. if (readIds.contains(metaEmail.getId())) {
  197. metaEmail.setRead(true);
  198. }
  199. });
  200. return metaEmails;
  201. }
  202. /**
  203. * 删除邮件
  204. *
  205. * @param userId 用户id
  206. * @param emailId 邮件id
  207. */
  208. private void delEmail(Long userId, Long emailId) {
  209. MetaEmailRecord metaEmailRecord = metaEmailRecordRepo.findByUserIdAndEmailId(userId, emailId);
  210. if (Objects.isNull(metaEmailRecord)) {
  211. metaEmailRecordRepo.save(new MetaEmailRecord(userId, emailId, true, true));
  212. return;
  213. }
  214. metaEmailRecord.setEmailDel(true);
  215. metaEmailRecordRepo.save(metaEmailRecord);
  216. }
  217. private void exceptionHandle(String userId, PublicScreenChatExceptionMsg msg) {
  218. log.error(JSON.toJSONString(msg));
  219. // 推送消息给该玩家
  220. websocketCommon.sendMessageTo(clients, JSON.toJSONString(msg), userId);
  221. }
  222. }