WebSocketEndpoint.java 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. package com.care.bms.websocket;
  2. import cn.hutool.json.JSONUtil;
  3. import com.care.common.util.ExUtil;
  4. import com.care.common.util.JsonUtil;
  5. import com.care.common.util.JwtUtils;
  6. import com.care.common.util.Result;
  7. import com.care.common.vo.UserLogindConvertVO;
  8. import io.jsonwebtoken.Claims;
  9. import io.swagger.annotations.ApiModelProperty;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  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/order/ws")
  25. @Component
  26. public class WebSocketEndpoint {
  27. private static final Logger logger = LoggerFactory.getLogger(WebSocketEndpoint.class);
  28. //用来存放每个客户端对应的BigScreenWebSocketEndpoint对象
  29. private static CopyOnWriteArraySet<WebSocketEndpoint> currentWebSocketSession = new CopyOnWriteArraySet<>();
  30. // 与某个客户端的连接会话,需要通过它来与客户端进行数据收发
  31. private Session session;
  32. //用于关联当前客户端和websocket会话的关系
  33. //电话作为登陆用户名
  34. private String phone;
  35. @ApiModelProperty("机构ID")
  36. private Long orgId;
  37. @ApiModelProperty("服务站ID,角色为坐席时,该字段可能未空")
  38. private Long 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. }
  62. }
  63. if (StringUtils.isEmpty(ts)) {
  64. closeSession(session, "-1", "连接失败,token为空");
  65. return;
  66. }
  67. Claims claims = JwtUtils.tokenParse(ts);
  68. if (claims != null) {
  69. UserLogindConvertVO vo = JSONUtil.toBean(claims.getSubject(), UserLogindConvertVO.class);
  70. if (vo != null) {
  71. this.phone = vo.getPhone();
  72. this.orgId = vo.getOrgId();
  73. this.stationId = vo.getStationId();
  74. } else{
  75. closeSession(session, "-1", "连接失败,token解析失败");
  76. return;
  77. }
  78. }
  79. logger.info("websocket会话建立:登录用户={}登录!",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={},登录用户={},退出websocket连接", session.getId(), this.phone);
  92. }
  93. @OnError
  94. public void onError(Session session, Throwable error) {
  95. logger.error("客户端id={},登录用户={},连接异常信息={}.", session.getId(), 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(Long orgId,Long stationId ,String message) throws IOException {
  106. for (WebSocketEndpoint endpoint : currentWebSocketSession) {
  107. Session session = endpoint.getSession();
  108. if (session.isOpen()) {
  109. if (endpoint.orgId == orgId){
  110. //发送消息
  111. try {
  112. session.getBasicRemote().sendText(message);
  113. } catch (IOException e) {
  114. logger.info("登录用户={} 发送数据失败,客户端连接已经断开.", endpoint.getPhone());
  115. }
  116. }
  117. }
  118. }
  119. }
  120. /**
  121. * 关闭session操作
  122. *
  123. * @param session
  124. * @param msg
  125. * @throws Exception
  126. */
  127. private void closeSession(Session session, String code, String msg) {
  128. try {
  129. if (session != null){
  130. if("-1".equals(code)){
  131. session.getBasicRemote().sendText(JsonUtil.toJson(Result.error(msg)));
  132. } else {
  133. session.getBasicRemote().sendText(JsonUtil.toJson(Result.success(msg)));
  134. }
  135. session.close();
  136. }
  137. } catch (Exception e) {
  138. logger.info("关闭连接异常", e.getCause());
  139. }
  140. }
  141. public Session getSession() {
  142. return session;
  143. }
  144. public String getPhone() {
  145. return phone;
  146. }
  147. }