当前位置:   article > 正文

基于springboot的websocket的使用_websocketfactory 依赖

websocketfactory 依赖

1.添加websocket依赖

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

2.springboot的启动类注册bean

  1. WebSocket配置类
  2. @Bean
  3. public ServerEndpointExporter serverEndpointExporter() {
  4. return new ServerEndpointExporter();
  5. }

3.websocket操作类:

  1. import org.slf4j.Logger;
  2. import org.slf4j.LoggerFactory;
  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.concurrent.ConcurrentHashMap;
  8. import java.util.concurrent.atomic.AtomicInteger;
  9. @ServerEndpoint(value = "/websocket/{id}")
  10. @Component
  11. public class Websocket{
  12. private static final Logger LOGGER = LoggerFactory.getLogger(Websocket.class);
  13. private static AtomicInteger onlineCount = new AtomicInteger(0);
  14. private static ConcurrentHashMap<String, Session> mesSessionMap = new ConcurrentHashMap<>();
  15. private static ConcurrentHashMap<String, Websocket> mesWebsocketMap = new ConcurrentHashMap<>();
  16. /**
  17. * 连接建立成功调用的方法
  18. */
  19. @OnOpen
  20. public void onOpen(@PathParam("id") String id, Session session) {
  21. onlineCount.incrementAndGet();
  22. mesSessionMap.put(id, session);
  23. mesWebsocketMap.put(id, this);
  24. LOGGER.info("有新连接加入:{},当前在线人数为:{}", session.getId(), onlineCount.get());
  25. }
  26. /**
  27. * 连接关闭调用的方法
  28. */
  29. @OnClose
  30. public void onClose(@PathParam("id") String id, Session session) {
  31. onlineCount.decrementAndGet();
  32. mesSessionMap.remove(id);
  33. mesWebsocketMap.remove(id);
  34. LOGGER.info("有一连接关闭:{},当前在线人数为:{}", session.getId(), onlineCount.get());
  35. }
  36. /**
  37. * 当发生错误时
  38. */
  39. @OnError
  40. public void onError(Session session, Throwable error) {
  41. LOGGER.error("发生错误", error);
  42. error.printStackTrace();
  43. }
  44. /**
  45. * 发送信息
  46. */
  47. public void sendMessage(String id, String json) {
  48. Session session = mesSessionMap.get(id);
  49. if (session != null) {
  50. session.getAsyncRemote().sendText(json);
  51. }
  52. }
  53. public static Websocket getWebSockets(String id) {
  54. Websocket webSockets = mesWebsocketMap.get(id);
  55. return webSockets;
  56. }
  57. /*
  58. * 收到客户端消息后调用的方法
  59. * @param message 客户端发送过来的消息
  60. * @param session 可选参数
  61. */
  62. @OnMessage
  63. public void onMessage(@PathParam("id") String id, String test, Session session) {
  64. System.out.println("来自客户端的消息:" + id + ";" + test);
  65. mesWebsocketMap.get(id).sendMessage(id, "json");
  66. }
  67. }

4.nginx支撑websocket配置,其中ip和port为自身的微服务ip和端口。(若该服务中又权限控制,做路劲过滤。)

  1. location /api/websocket/ {
  2. proxy_pass http://ip:port/;
  3. proxy_http_version 1.1;
  4. proxy_set_header Upgrade websocket;
  5. proxy_set_header Connection upgrade;
  6. proxy_connect_timeout 75;
  7. proxy_read_timeout 1800s;
  8. proxy_send_timeout 1800s;
  9. add_header 'Access-Control-Allow-Origin' '$http_origin' always;
  10. add_header 'Access-Control-Allow-Credentials' 'true' always;
  11. add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE' always;
  12. add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range' always;
  13. add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range' always;
  14. if ($request_method = 'OPTIONS') {
  15. add_header 'Access-Control-Allow-Origin' '$http_origin' always;
  16. add_header 'Access-Control-Allow-Credentials' 'true' always;
  17. add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE' always;
  18. add_header 'Access-Control-Allow-Headers' 'Pragma,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range' always;
  19. add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range' always;
  20. add_header 'Access-Control-Max-Age' '1728000' always;
  21. add_header 'Content-Type' 'text/plain; charset=utf-8' always;
  22. add_header 'Content-Length' 0 always;
  23. return 204;
  24. }
  25. }

5.1测试如下:测试工具为Apipost

建立连接如图:

 5.2测试发送接口(对接websocket的onMessage接口)

 

 

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

闽ICP备14008679号