WebSocketServer.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package com.gz.websocket;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.stereotype.Component;
  4. import javax.websocket.*;
  5. import javax.websocket.server.PathParam;
  6. import javax.websocket.server.ServerEndpoint;
  7. import java.util.Map;
  8. import java.util.concurrent.ConcurrentHashMap;
  9. /**
  10. * 在线WebSocket
  11. * @author LiuchangLan
  12. * @date 2020/8/7 10:02
  13. */
  14. @ServerEndpoint("/webSocket/{adminId}")
  15. @Component
  16. @Slf4j
  17. public class WebSocketServer {
  18. /**
  19. * @description 存放所有在线的客户端 static保证线程安全
  20. * @author LiuChangLan
  21. * @since 2020/8/7 10:03
  22. */
  23. public static Map<String, Session> clients = new ConcurrentHashMap<>();
  24. /**
  25. * @description 连接
  26. * @author LiuChangLan
  27. * @since 2020/8/7 10:09
  28. */
  29. @OnOpen
  30. public void onOpen(Session session, @PathParam("adminId")String adminId){
  31. clients.put(adminId,session);
  32. log.info("客户端{}连接了 当前在线人数:{}",adminId,clients.size());
  33. }
  34. /**
  35. * @description 断开连接
  36. * @author LiuChangLan
  37. * @since 2020/8/7 10:09
  38. */
  39. @OnClose
  40. public void onClose(Session session, @PathParam("adminId")String adminId){
  41. clients.remove(adminId);
  42. log.info("客户端{}断开了 当前在线人数:{}",adminId,clients.size());
  43. }
  44. /**
  45. * @description 发送错误
  46. * @author LiuChangLan
  47. * @since 2020/8/7 10:09
  48. */
  49. @OnError
  50. public void onError(Throwable throwable){
  51. throwable.printStackTrace();
  52. }
  53. /**
  54. * @description 接受消息
  55. * @author LiuChangLan
  56. * @since 2020/8/7 10:09
  57. */
  58. @OnMessage
  59. public void onMessage(@PathParam("adminId")String adminId, String message){
  60. log.info("服务端收到客户端{}发来的消息: {}",adminId, message);
  61. }
  62. public void sendMessage(String adminId,String message){
  63. Session session = clients.get(adminId);
  64. if (session != null){
  65. session.getAsyncRemote().sendText(message);
  66. }
  67. }
  68. }