当前位置:   article > 正文

spring-boot-starter-websocket创建服务

spring-boot-starter-websocket

WebSocketApplicationContextAware 层

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Component
@Lazy(false)
public class WebSocketApplicationContextAware implements ApplicationContextAware {

    private static ApplicationContext APPLICATION_CONTEXT;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        APPLICATION_CONTEXT = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return APPLICATION_CONTEXT;
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

WebSocketConfig层

package com.dataexa.qt.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
@EnableWebSocket
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

WebSocket类

@Slf4j
@Component  //注册到容器中
@ServerEndpoint("/webSocket")  //接收websocket请求路径
public class WebSocket {

    //定义一个websocket容器存储session,即存放所有在线的socket连接
    private static CopyOnWriteArraySet<Session> webSocketSet = new CopyOnWriteArraySet<>();

    private static ApplicationContext applicationContext = WebSocketApplicationContextAware.getApplicationContext();

    private Neo4jService neo4jService = (Neo4jService) applicationContext.getBean(Neo4jService.class);

 

    //处理连接建立
    @OnOpen
    public void opOpen(Session session) {
        log.info("【有新的客户端连接了】:{}", session.getId());
        //将新用户加入在线组
        webSocketSet.add(session);
        log.info("【websocket消息】有新的连接,总数:{}", webSocketSet.size());
   
    }


    @Value("${spring.socket.url}")
    private String url;

/*
这一段可加可不加  是用于连接socket的 相当与客户端
*/
    //启动链接第三方socket //监听在线状态 5 * * * * ? 5秒 , 0 0/5 * * * ? 5分钟
    @Scheduled(cron = "0 0/5 * * * ?")
    public  void webSocketStata(){
        try {
            BaseWebsocketClient baseWebsocketClient= new BaseWebsocketClient( new URI(url));
            baseWebsocketClient.connect();
            while (!baseWebsocketClient.getReadyState().equals(ReadyState.OPEN)){
                log.info("链接中....");
                Thread.sleep(1000);
                break;
            }
            log.info("状态 :{}",baseWebsocketClient.isOpen());
            JSONObject jsonObject=new JSONObject();
            if (baseWebsocketClient.isOpen()){
                jsonObject.put("code",5);
                jsonObject.put("data","green");
                sendMessage(jsonObject.toJSONString());
            }else {
                jsonObject.put("code",5);
                jsonObject.put("data","red");
                sendMessage(jsonObject.toJSONString());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


    //处理连接关闭
    @OnClose
    public void Onclose(Session session) {
        webSocketSet.remove(session);
        log.info("【websocket消息】连接断开,总数:{}", webSocketSet.size());
    }

    //接受消息
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("【websocket消息】收到客户端发来的消息:{}", message);
        //根据用户发送回去
      session.getBasicRemote().sendText("发送信息");
    }

    //发消息调用即可
    public void sendMessage(String message) {
        try {
            for (Session session1 : webSocketSet) {
                session1.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88

依赖

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

启动类注解

@EnableScheduling 这是定时任务注解
@EnableWebSocket  socket注解
  • 1
  • 2

以上两者同时运用是就需要全部加上注解,单独之加单独即可.

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

闽ICP备14008679号