WebSocketServer.java 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. package com.keao.edu.user.controller;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import org.apache.commons.lang3.StringUtils;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.stereotype.Component;
  8. import javax.websocket.*;
  9. import javax.websocket.server.PathParam;
  10. import javax.websocket.server.ServerEndpoint;
  11. import java.io.IOException;
  12. import java.util.concurrent.ConcurrentHashMap;
  13. @ServerEndpoint(value = "/ws/{userId}")
  14. @Component
  15. public class WebSocketServer {
  16. private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
  17. /**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/
  18. private static int onlineCount = 0;
  19. /**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/
  20. private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
  21. /**与某个客户端的连接会话,需要通过它来给客户端发送数据*/
  22. private Session session;
  23. /**接收userId*/
  24. private String userId="";
  25. /**
  26. * 连接建立成功调用的方法*/
  27. @OnOpen
  28. public void onOpen(Session session,@PathParam("userId") String userId) {
  29. this.session = session;
  30. this.userId=userId;
  31. if(webSocketMap.containsKey(userId)){
  32. webSocketMap.remove(userId);
  33. webSocketMap.put(userId,this);
  34. //加入set中
  35. }else{
  36. webSocketMap.put(userId,this);
  37. //加入set中
  38. addOnlineCount();
  39. //在线数加1
  40. }
  41. log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());
  42. try {
  43. sendMessage("连接成功");
  44. } catch (IOException e) {
  45. log.error("用户:"+userId+",网络异常!!!!!!");
  46. }
  47. }
  48. /**
  49. * 连接关闭调用的方法
  50. */
  51. @OnClose
  52. public void onClose() {
  53. if(webSocketMap.containsKey(userId)){
  54. webSocketMap.remove(userId);
  55. //从set中删除
  56. subOnlineCount();
  57. }
  58. log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
  59. }
  60. /**
  61. * 收到客户端消息后调用的方法
  62. *
  63. * @param message 客户端发送过来的消息*/
  64. @OnMessage
  65. public void onMessage(String message, Session session) {
  66. log.info("用户消息:"+userId+",报文:"+message);
  67. //可以群发消息
  68. //消息保存到数据库、redis
  69. if(StringUtils.isNotBlank(message)){
  70. try {
  71. //解析发送的报文
  72. JSONObject jsonObject = JSON.parseObject(message);
  73. //追加发送人(防止串改)
  74. jsonObject.put("fromUserId",this.userId);
  75. String toUserId=jsonObject.getString("toUserId");
  76. //传送给对应toUserId用户的websocket
  77. if(StringUtils.isNotBlank(toUserId)&&webSocketMap.containsKey(toUserId)){
  78. webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
  79. }else{
  80. log.error("请求的userId:"+toUserId+"不在该服务器上");
  81. //否则不在这个服务器上,发送到mysql或者redis
  82. }
  83. }catch (Exception e){
  84. e.printStackTrace();
  85. }
  86. }
  87. }
  88. /**
  89. *
  90. * @param session
  91. * @param error
  92. */
  93. @OnError
  94. public void onError(Session session, Throwable error) {
  95. log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
  96. error.printStackTrace();
  97. }
  98. /**
  99. * 实现服务器主动推送
  100. */
  101. public void sendMessage(String message) throws IOException {
  102. this.session.getBasicRemote().sendText(message);
  103. }
  104. /**
  105. * 发送自定义消息
  106. * */
  107. public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException {
  108. log.info("发送消息到:"+userId+",报文:"+message);
  109. if(StringUtils.isNotBlank(userId)&&webSocketMap.containsKey(userId)){
  110. webSocketMap.get(userId).sendMessage(message);
  111. }else{
  112. log.error("用户"+userId+",不在线!");
  113. }
  114. }
  115. public static synchronized int getOnlineCount() {
  116. return onlineCount;
  117. }
  118. public static synchronized void addOnlineCount() {
  119. WebSocketServer.onlineCount++;
  120. }
  121. public static synchronized void subOnlineCount() {
  122. WebSocketServer.onlineCount--;
  123. }
  124. }