WebSocket.java 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. package com.sqx.modules.chats.controller;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.sqx.modules.chats.entity.ChatsContent;
  5. import com.sqx.modules.chats.service.ChatsContentService;
  6. import com.sqx.modules.chats.utils.DateUtil;
  7. import org.apache.commons.lang.StringUtils;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.stereotype.Component;
  12. import javax.websocket.*;
  13. import javax.websocket.server.PathParam;
  14. import javax.websocket.server.ServerEndpoint;
  15. import java.io.IOException;
  16. import java.util.Map;
  17. import java.util.concurrent.ConcurrentHashMap;
  18. /**
  19. * WebSocket聊天实现
  20. */
  21. @Component
  22. @ServerEndpoint("/websocket/{wxUserId}")
  23. public class WebSocket {
  24. private Logger logger = LoggerFactory.getLogger(this.getClass());
  25. //通过类似GET请求方式传递参数的方法(服务端采用第二种方法"WebSocketHandler"实现)
  26. //websocket = new WebSocket("ws://127.0.0.1:18080/testWebsocket?id=23&name=Lebron");
  27. /**
  28. * 在线人数
  29. */
  30. public static int onlineNumber = 0;
  31. /**
  32. * 以用户的id为key,WebSocket为对象保存起来
  33. */
  34. private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
  35. /**
  36. * 会话
  37. */
  38. private Session session;
  39. /**
  40. * 用户id
  41. */
  42. private String wxUserId;
  43. //这里使用静态,让 service 属于类
  44. private static ChatsContentService chatContentService;
  45. //注入的时候,给类的 service 注入
  46. @Autowired
  47. public void setWxChatContentService(ChatsContentService chatContentService) {
  48. WebSocket.chatContentService = chatContentService;
  49. }
  50. /**
  51. * 建立连接
  52. *
  53. * @param session
  54. */
  55. @OnOpen
  56. public void onOpen(@PathParam("wxUserId") String wxUserId, Session session) {
  57. onlineNumber++;
  58. logger.info("现在来连接的客户id:" + wxUserId);
  59. this.wxUserId = wxUserId;
  60. this.session = session;
  61. logger.info("有新连接加入! 当前在线人数" + onlineNumber);
  62. try {
  63. //把自己的信息加入到map当中去
  64. clients.remove(wxUserId);
  65. clients.put(wxUserId, this);
  66. /*sendMessageTo("恭喜你连接成功!",wxUserId);*/
  67. } catch (Exception e) {
  68. logger.info(wxUserId + "上线的时候通知所有人发生了错误");
  69. }
  70. }
  71. @OnError
  72. public void onError(Session session, Throwable error) {
  73. logger.info("服务端发生了错误" + error.getMessage());
  74. }
  75. /**
  76. * 连接关闭
  77. */
  78. @OnClose
  79. public void onClose() {
  80. onlineNumber--;
  81. //webSockets.remove(this);
  82. clients.remove(wxUserId);
  83. logger.info("有连接关闭! 当前在线人数" + onlineNumber);
  84. }
  85. /**
  86. * 接收客户端的消息,并把消息发送给所有连接的会话
  87. */
  88. @OnMessage
  89. public void onMessage(String message) {
  90. try {
  91. //解析聊天内容
  92. JSONObject jsonObject = JSON.parseObject(message);
  93. String type = jsonObject.getString("type");
  94. String content = jsonObject.getString("content");
  95. String sendType = jsonObject.getString("sendType");
  96. String userId = jsonObject.getString("userId");
  97. String storeId = jsonObject.getString("storeId");
  98. Long chatId = Long.valueOf(jsonObject.getString("chatId")); //会话id
  99. if ("1".equals(sendType)) {
  100. logger.info("用户发送消息:" + message);
  101. } else {
  102. logger.info("客服发送消息:" + message);
  103. }
  104. if(StringUtils.isNotEmpty(userId) && !"null".equals(userId)){
  105. //聊天记录
  106. ChatsContent wxChatContent = new ChatsContent();
  107. wxChatContent.setContent(content);
  108. wxChatContent.setType(Integer.valueOf(type));
  109. wxChatContent.setSendType(Integer.valueOf(sendType));
  110. wxChatContent.setUserId(Long.valueOf(userId));
  111. wxChatContent.setStoreId(Long.valueOf(storeId));
  112. wxChatContent.setChatId(chatId);
  113. wxChatContent.setCreateTime(DateUtil.createTime()); //创建时间
  114. wxChatContent.setStatus(1); //未读
  115. //判断对方是否在线,消息设为已读
  116. for (WebSocket item : clients.values()) {
  117. if ("1".equals(sendType)) { //用户发送
  118. if (item.wxUserId.equals(storeId)) {
  119. // wxChatContent.setStatus(2); //已读
  120. wxChatContent.setStatus(1); //不自动设置为已读
  121. item.session.getAsyncRemote().sendText(message);
  122. }
  123. }else {
  124. if (item.wxUserId.equals(userId)) {
  125. // wxChatContent.setStatus(2); //已读
  126. wxChatContent.setStatus(1); //不自动设置为已读
  127. item.session.getAsyncRemote().sendText(message);
  128. }
  129. }
  130. }
  131. //保存消息内容
  132. chatContentService.saveBody(wxChatContent);
  133. }
  134. } catch (Exception e) {
  135. logger.info("发生了错误了");
  136. }
  137. }
  138. public void sendMessageTo(String message, String wxUserId) throws IOException {
  139. for (WebSocket item : clients.values()) {
  140. if (item.wxUserId.equals(wxUserId)) {
  141. item.session.getAsyncRemote().sendText(message);
  142. break;
  143. }
  144. }
  145. }
  146. public void sendMessageAll(String message, String FromUserName) throws IOException {
  147. for (WebSocket item : clients.values()) {
  148. item.session.getAsyncRemote().sendText(message);
  149. }
  150. }
  151. public static synchronized int getOnlineCount() {
  152. return onlineNumber;
  153. }
  154. }