WebSocketServer.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package com.zy.bms.websocket;
  2. import org.springframework.stereotype.Component;
  3. import javax.websocket.*;
  4. import javax.websocket.server.PathParam;
  5. import javax.websocket.server.ServerEndpoint;
  6. import java.io.IOException;
  7. import java.util.LinkedList;
  8. import java.util.List;
  9. import java.util.concurrent.ConcurrentHashMap;
  10. @Component
  11. @ServerEndpoint("/webSocket/{deviceId}")
  12. public class WebSocketServer {
  13. /**
  14. * 存放每个客户端对应的MyWebSocket对象。
  15. * key : 设备ID
  16. * value : 实时接收该设备的web端session
  17. */
  18. private static ConcurrentHashMap<String, List<Session>> webSocketMap = new ConcurrentHashMap<>();
  19. /**
  20. * 连接成功
  21. */
  22. @OnOpen
  23. public void onOpen(Session session, @PathParam("deviceId") String deviceId) {
  24. //如果该设备没有web端查看,则初始化
  25. if (!webSocketMap.containsKey(deviceId)) webSocketMap.put(deviceId, new LinkedList<>());
  26. //添加到集合中
  27. webSocketMap.get(deviceId).add(session);
  28. }
  29. /**
  30. * 连接关闭
  31. */
  32. @OnClose
  33. public void onClose(Session session, @PathParam("deviceId") String deviceId) {
  34. webSocketMap.get(deviceId).remove(session);
  35. }
  36. /**
  37. * 连接错误
  38. */
  39. @OnError
  40. public void onError(Session session, Throwable error, @PathParam("deviceId") String deviceId) {
  41. webSocketMap.get(deviceId).remove(session);
  42. }
  43. /**
  44. * 群发消息
  45. */
  46. public void massMessage(String deviceId, String message) {
  47. List<Session> sessions = webSocketMap.get(deviceId);
  48. if (sessions == null || sessions.isEmpty()) return;
  49. // 遍历客户端 发送消息
  50. for (Session session : sessions) {
  51. sendMessage(session, message);
  52. }
  53. }
  54. /**
  55. * 实现服务器主动推送
  56. */
  57. private void sendMessage(Session session, String message) {
  58. try {
  59. session.getBasicRemote().sendText(message);
  60. } catch (IOException e) {
  61. e.printStackTrace();
  62. }
  63. }
  64. }