当前位置:   article > 正文

Java -- springboot 配置 Websocket_spring boot websocket rxjava

spring boot websocket rxjava

1.配置依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-websocket</artifactId>
  4. </dependency>

2、配置类

  1. package com.vim.common.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.socket.server.standard.ServerEndpointExporter;
  5. @Configuration
  6. public class WebSocketConfig {
  7. @Bean
  8. public ServerEndpointExporter serverEndpointExporter() {
  9. return new ServerEndpointExporter();
  10. }
  11. }

3、消息类别

  1. package com.vim.common.push;
  2. public class WebSocketMsg {
  3. public enum MsgType{
  4. ONLINE_COUNT, NOTIFY;
  5. }
  6. /**
  7. * 消息类型
  8. */
  9. private MsgType type;
  10. /**
  11. * 消息内容
  12. */
  13. private Object data;
  14. public WebSocketMsg(MsgType type, Object data) {
  15. this.type = type;
  16. this.data = data;
  17. }
  18. public MsgType getType() {
  19. return type;
  20. }
  21. public void setType(MsgType type) {
  22. this.type = type;
  23. }
  24. public Object getData() {
  25. return data;
  26. }
  27. public void setData(Object data) {
  28. this.data = data;
  29. }
  30. }

4、消息服务器

  1. package com.vim.common.push;
  2. import com.alibaba.fastjson.JSONObject;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.stereotype.Component;
  6. import javax.websocket.OnClose;
  7. import javax.websocket.OnOpen;
  8. import javax.websocket.Session;
  9. import javax.websocket.server.PathParam;
  10. import javax.websocket.server.ServerEndpoint;
  11. import java.util.HashSet;
  12. import java.util.concurrent.atomic.AtomicLong;
  13. @ServerEndpoint("/websocket/{userId}")
  14. @Component
  15. public class WebSocketServer {
  16. private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
  17. private Session session;
  18. private String userId;
  19. public String getUserId() {
  20. return userId;
  21. }
  22. public void setUserId(String userId) {
  23. this.userId = userId;
  24. }
  25. /**
  26. * 在线人数
  27. */
  28. private static AtomicLong onlineCount = new AtomicLong(0);
  29. /**
  30. * 客户端集合
  31. */
  32. private static HashSet<WebSocketServer> servers = new HashSet<>();
  33. @OnOpen
  34. public void onOpen(Session session, @PathParam("userId") String userId) {
  35. this.session = session;
  36. this.userId = userId;
  37. boolean online = false;
  38. for(WebSocketServer server:servers){
  39. if(server.getUserId().equals(userId)){
  40. online = true;
  41. }
  42. }
  43. if(!servers.contains(this) && !online){
  44. servers.add(this);
  45. onlineCount.incrementAndGet();
  46. sendMessage(new WebSocketMsg(WebSocketMsg.MsgType.ONLINE_COUNT, onlineCount.get()));
  47. }
  48. }
  49. @OnClose
  50. public void onClose() {
  51. servers.remove(this);
  52. onlineCount.decrementAndGet();
  53. sendMessage(new WebSocketMsg(WebSocketMsg.MsgType.ONLINE_COUNT, onlineCount.get()));
  54. }
  55. /**
  56. * 发送消息到指定用户
  57. */
  58. public static void sendMessage(WebSocketMsg message, String userId) {
  59. for (WebSocketServer server : servers) {
  60. try {
  61. if(server.getUserId().equals(userId)){
  62. server.session.getBasicRemote().sendText(JSONObject.toJSONString(message));
  63. }
  64. } catch (Exception e) {
  65. logger.error("系统异常!", e);
  66. }
  67. }
  68. }
  69. /**
  70. * 群发消息
  71. */
  72. public static void sendMessage(WebSocketMsg message) {
  73. for (WebSocketServer server : servers) {
  74. try {
  75. server.session.getBasicRemote().sendText(JSONObject.toJSONString(message));
  76. } catch (Exception e) {
  77. logger.error("系统异常!", e);
  78. }
  79. }
  80. }
  81. }

5、html代码

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>通用项目模板</title>
  5. </head>
  6. <body>
  7. </body>
  8. <script>
  9. var websocket = null;
  10. if ('WebSocket' in window) {
  11. websocket = new WebSocket("ws://"+window.location.host+"/websocket/11");
  12. }
  13. websocket.onopen = onOpen;
  14. websocket.onmessage = onMessage;
  15. websocket.onerror = onError;
  16. websocket.onclose = onClose;
  17. function onMessage(event) {
  18. var result = JSON.parse(event.data);
  19. if(result.type == "ONLINE_COUNT"){
  20. }
  21. if(result.type == "NOTIFY"){
  22. }
  23. }
  24. function onOpen(event) {}
  25. function onError() {}
  26. function onClose() {}
  27. </script>
  28. </html>

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/717246
推荐阅读
相关标签
  

闽ICP备14008679号