BigScreenWebSocketEndpoint.java 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. package com.care.bigscreen.websocket;
  2. import cn.hutool.json.JSONUtil;
  3. import com.care.common.vo.UserLogindConvertVO;
  4. import com.care.util.ExUtil;
  5. import com.care.util.JsonUtil;
  6. import com.care.util.JwtUtils;
  7. import com.care.util.Result;
  8. import io.jsonwebtoken.Claims;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.stereotype.Component;
  13. import org.springframework.util.StringUtils;
  14. import javax.websocket.*;
  15. import javax.websocket.server.ServerEndpoint;
  16. import java.io.IOException;
  17. import java.util.concurrent.CopyOnWriteArraySet;
  18. /**
  19. * Swagger2配置
  20. *
  21. * @author stw
  22. * @version 1.0.0 创建于 2021/5/24
  23. **/
  24. @ServerEndpoint("/bms/bigscreen/ws")
  25. @Component
  26. public class BigScreenWebSocketEndpoint {
  27. private static final Logger logger = LoggerFactory.getLogger(BigScreenWebSocketEndpoint.class);
  28. @Autowired
  29. JwtUtils jwtUtils;
  30. //用来存放每个客户端对应的BigScreenWebSocketEndpoint对象
  31. private static CopyOnWriteArraySet<BigScreenWebSocketEndpoint> currentWebSocketSession = new CopyOnWriteArraySet<>();
  32. // 与某个客户端的连接会话,需要通过它来与客户端进行数据收发
  33. private Session session;
  34. //用于关联当前客户端和websocket会话的关系
  35. //电话作为登陆用户名
  36. private String phone;
  37. //服务站ID
  38. private String stationId;
  39. /**
  40. * websocket 连接打开操作
  41. *
  42. * @param session websocket会话对象
  43. */
  44. @OnOpen
  45. public void webSocketOnOpen(Session session) {
  46. try {
  47. //校验参数
  48. String requestParamString = session.getQueryString();
  49. if (StringUtils.isEmpty(requestParamString)) {
  50. closeSession(session, "-1", "连接失败,token为空");
  51. return;
  52. }
  53. //建立websocket和登录用户、站点ID的关联关系
  54. //从token中解析出登录用户的信息
  55. String[] keyValues = requestParamString.split("&");
  56. //取出token 字符串
  57. String ts = null;
  58. for (String t : keyValues) {
  59. if (t.startsWith("token=")) {
  60. ts = t.replaceAll("token=", "");
  61. } else if (t.startsWith("stationId=")) {
  62. stationId = t.replaceAll("stationId=", "");
  63. }
  64. }
  65. if (StringUtils.isEmpty(ts) || StringUtils.isEmpty(stationId)) {
  66. closeSession(session, "-1", "连接失败,token或stationId为空");
  67. return;
  68. }
  69. Claims claims = jwtUtils.tokenParse(ts);
  70. if (claims != null) {
  71. UserLogindConvertVO vo = JSONUtil.toBean(claims.getSubject(), UserLogindConvertVO.class);
  72. if (vo != null) {
  73. this.phone = vo.getPhone();
  74. } else{
  75. closeSession(session, "-1", "连接失败,token解析失败");
  76. return;
  77. }
  78. }
  79. logger.info("websocket会话建立:服务站ID={},登录用户={}登录!", this.stationId,this.phone);
  80. this.session = session;
  81. currentWebSocketSession.add(this);
  82. } catch (Exception e) {
  83. closeSession(session, "-1", "连接失败,token为空");
  84. logger.error("websocket会话建立异常:"+ ExUtil.exToDetail(e));
  85. }
  86. }
  87. @OnClose
  88. public void onClose(Session session) {
  89. //移除连接
  90. currentWebSocketSession.remove(this);
  91. logger.info("客户端断开连接,客户端id={},服务站ID={},登录用户={},退出websocket连接", session.getId(), this.stationId, this.phone);
  92. }
  93. @OnError
  94. public void onError(Session session, Throwable error) {
  95. logger.error("客户端id={},服务站ID={},登录用户={},连接异常信息={}.", session.getId(), this.stationId, this.phone, error.getCause());
  96. }
  97. @OnMessage
  98. public void onMessage(String message, Session session) throws Exception {
  99. // logger.info("Receive a message from client: " + message);
  100. // 页面传过来的消息不做任何处理
  101. logger.info("收到来自" + session.getId() + "的消息" + message);
  102. //返回消息给Web Socket客户端(浏览器)
  103. // sendMessage(message);
  104. }
  105. public static void sendMessage(String message) throws IOException {
  106. for (BigScreenWebSocketEndpoint endpoint : currentWebSocketSession) {
  107. Session session = endpoint.getSession();
  108. if (session.isOpen()) {
  109. //发送消息
  110. try {
  111. session.getBasicRemote().sendText(message);
  112. } catch (IOException e) {
  113. logger.info("给服务站ID={},登录用户={} 发送数据失败,客户端连接已经断开.", endpoint.getStationId(), endpoint.getPhone());
  114. }
  115. }
  116. }
  117. }
  118. /**
  119. * 给客户端发送消息的方法
  120. *
  121. * @param stationId 服务站ID
  122. * @param msg 发送的信息
  123. */
  124. public static void sendMsgToFront(String stationId,String msg) {
  125. //根据服务站ID,匹配连接并发送消息
  126. for (BigScreenWebSocketEndpoint endpoint : currentWebSocketSession) {
  127. Session session = endpoint.getSession();
  128. if (session.isOpen() && stationId.equals(endpoint.getStationId())) {
  129. //发送消息
  130. try {
  131. session.getBasicRemote().sendText(msg);
  132. } catch (IOException e) {
  133. logger.info("给服务站ID={},登录用户={} 发送数据失败,客户端连接已经断开.", endpoint.getStationId(), endpoint.getPhone());
  134. }
  135. }
  136. }
  137. }
  138. /**
  139. * 关闭session操作
  140. *
  141. * @param session
  142. * @param msg
  143. * @throws Exception
  144. */
  145. private void closeSession(Session session, String code, String msg) {
  146. try {
  147. if (session != null){
  148. if("-1".equals(code)){
  149. session.getBasicRemote().sendText(JsonUtil.toJson(Result.error(msg)));
  150. } else {
  151. session.getBasicRemote().sendText(JsonUtil.toJson(Result.success(msg)));
  152. }
  153. session.close();
  154. }
  155. } catch (Exception e) {
  156. logger.info("关闭连接异常", e.getCause());
  157. }
  158. }
  159. public Session getSession() {
  160. return session;
  161. }
  162. public String getPhone() {
  163. return phone;
  164. }
  165. public String getStationId() {
  166. return stationId;
  167. }
  168. }