当前位置:   article > 正文

java WebSocket带参数处理使用_java websocket 传递参数

java websocket 传递参数

1、webSocket实现代码

  1. @Component
  2. public class WebSocketStompConfig {
  3. //这个bean的注册,用于扫描带有@ServerEndpoint的注解成为websocket
  4. // ,如果你使用外置的tomcat就不需要该配置文件
  5. @Bean
  6. public ServerEndpointExporter serverEndpointExporter() {
  7. return new ServerEndpointExporter();
  8. }
  9. }

  1. @Component
  2. @ServerEndpoint(value = "/webSocket")
  3. @Slf4j
  4. public class WebSocket {
  5. private static int onlineCount = 0;
  6. private static ConcurrentHashMap<String, Set<Session>> webSocketMap = new ConcurrentHashMap<>();
  7. private Session session;
  8. @OnOpen
  9. public void onOpen(Session session) {
  10. this.session = session;
  11. // 获取URL中的参数
  12. Map<String, List<String>> params = session.getRequestParameterMap();
  13. List<String> funcTypes = params.get("funcType");
  14. if (!funcTypes.isEmpty()) {
  15. // 取出funcType参数的值
  16. String funcType = funcTypes.get(0);
  17. if(webSocketMap.containsKey(funcType)){
  18. webSocketMap.get(funcType).add(session);
  19. }else{
  20. Set<Session> sessionSet = new HashSet<>();
  21. sessionSet.add(session);
  22. webSocketMap.put(funcType,sessionSet);
  23. }
  24. }
  25. System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
  26. }
  27. @OnClose
  28. public void onClose(){
  29. webSocketMap=new ConcurrentHashMap<>();
  30. log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
  31. }
  32. @OnMessage
  33. public void onMessage(String message, Session session) {
  34. System.out.println("来自客户端的消息:" + message);
  35. }
  36. @OnError
  37. public void onError(Session session, Throwable error) {
  38. System.out.println("发生错误");
  39. error.printStackTrace();
  40. }
  41. public static void sendMessage(Session session, String message) throws IOException {
  42. session.getBasicRemote().sendText(message);
  43. }
  44. public static synchronized int getOnlineCount() {
  45. return onlineCount;
  46. }
  47. public static synchronized void addOnlineCount() {
  48. WebSocket.onlineCount++;
  49. }
  50. public static synchronized void subOnlineCount() {
  51. WebSocket.onlineCount--;
  52. }
  53. public static void setOnlineCount(int onlineCount) {
  54. WebSocket.onlineCount = onlineCount;
  55. }
  56. public static ConcurrentHashMap<String, Set<Session>> getWebSocketMap() {
  57. return webSocketMap;
  58. }
  59. public static void setWebSocketMap(ConcurrentHashMap<String, Set<Session>> webSocketMap) {
  60. WebSocket.webSocketMap = webSocketMap;
  61. }
  62. public Session getSession() {
  63. return session;
  64. }
  65. public void setSession(Session session) {
  66. this.session = session;
  67. }
  68. /**
  69. * 发送自定义消息
  70. * */
  71. public static void sendInfo(String message,String funcType) throws Exception {
  72. if(webSocketMap.containsKey(funcType)){
  73. Set<Session> sessionSet = webSocketMap.get(funcType);
  74. if(sessionSet!=null){
  75. for (Session session : sessionSet) {
  76. if(session.getBasicRemote()!=null){
  77. session.getBasicRemote().sendText(message);
  78. }
  79. }
  80. }
  81. }else{
  82. log.error("订阅类型:"+funcType+",不存在!");
  83. throw new Exception("连接已关闭,请刷新页面后重试");
  84. }
  85. }
  86. }

二、java代码调用,往websocker赋数据

WebSocket.sendInfo(JSON.toJSONString("sdfasd232"),"3");

三、测试是否连接成功以及推送信息

四、前端代码处理

  1. /**
  2. * 初始化websocket连接
  3. */
  4. function initWebSocket() {
  5. var websocket = null;
  6. if('WebSocket' in window) {
  7. websocket = new WebSocket("ws://127.0.0.1:8080/webSocket?funcType=3" );
  8. } else {
  9. alert("该浏览器不支持websocket!");
  10. }
  11. websocket.onopen = function(event) {
  12. console.log("建立连接");
  13. websocket.send('Hello WebSockets!');
  14. }
  15. websocket.onclose = function(event) {
  16. console.log('连接关闭')
  17. reconnect(); //尝试重连websocket
  18. }
  19. //建立通信后,监听到后端的数据传递
  20. websocket.onmessage = function(event) {
  21. let data = JSON.parse(event.data);
  22. //业务处理....
  23. if(data.step == 1){
  24. alert(data.msg);
  25. }
  26. }
  27. websocket.onerror = function() {
  28. // notify.warn("websocket通信发生错误!");
  29. // initWebSocket()
  30. }
  31. window.onbeforeunload = function() {
  32. websocket.close();
  33. }
  34. // 重连
  35. function reconnect() {
  36. console.log("正在重连");
  37. // 进行重连
  38. setTimeout(function () {
  39. initWebSocket();
  40. }, 1000);
  41. }

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号