SprngBoot2整合websocket实现实时向前端发送数据

一次使用websocket体验…

  1. 在pom.xml中引入

     <!-- websocket -->
     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-websocket</artifactId>
     </dependency>
    
  2. 添加websocket配置类

     /**
      * WebSocket配置
      */
     @Configuration
     public class WebSocketConfig {
    
         /**
          * 用途:扫描并注册所有携带@ServerEndpoint注解的实例。 
          */
         @Bean
         public ServerEndpointExporter serverEndpointExporter() {
             return new ServerEndpointExporter();
         }
     
         /**
          * 支持注入其他类
          */
         @Bean
         public MyEndpointConfigure newMyEndpointConfigure (){
             return new MyEndpointConfigure ();
         }
     }
    
  3. 解决部署发布时的异常 MyEndpointConfigure

     /**
      * 解决注入其他类的问题
      * 以websocketConfig.java注册的bean是由自己管理的,需要使用配置托管给spring管理
      */
     public class MyEndpointConfigure extends ServerEndpointConfig.Configurator implements ApplicationContextAware {
    
         private static volatile BeanFactory context;
     
         @Override
         public <T> T getEndpointInstance(Class<T> clazz){
             return context.getBean(clazz);
         }
     
         @Override
         public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
             MyEndpointConfigure.context = applicationContext;
         }
     }
    
  4. WebSocket获取实时监控H5面板-并输出到Web页面

     	@Slf4j
     	@Component
     	@ServerEndpoint(value = "/web/socket", configurator = MyEndpointConfigure.class)
     	public class H5WSServer {
     
     	    // 与某个客户端的连接会话,需要通过它来给客户端发送数据
     	    private Session session;
     	    // concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
     	    private static CopyOnWriteArraySet<H5WSServer> webSocketSet = new CopyOnWriteArraySet<>();
     	
     	    // 连接建立成功调用的方法
     	    @OnOpen
     	    public void onOpen(Session session) {
     	        this.session = session;
     	        webSocketSet.add(this); // 加入set中
     	        try {
     	            sendMessage("您已成功连接!");
     	        } catch (IOException e) {
     	           log.error("-----onOpen---------err:" + e);
     	        }
         }
     
         // 连接关闭调用的方法
         @OnClose
         public void onClose(Session session) {
             webSocketSet.remove(this); // 从set中删除
         }
     
         // 发生错误时调用
         @OnError
         public void onError(Session session, Throwable e) {
             log.error("------onError-------err:" + e);
         }
     
         // 服务器接收到客户端消息时调用的方法
         @OnMessage
         public void onMessage(String message, Session session) {
             for (H5bpWSServer item : webSocketSet) {
                 try {
                     if(item.session==session){
                         item.sendMessage(message);
                     }
                 } catch (IOException e) {
                     log.error("-----onMessage---------err:" + e);
                 }
             }
         }
     
         // 发送消息
         public void sendMessage(String message) throws IOException {
             this.session.getBasicRemote().sendText(message);
             // this.session.getAsyncRemote().sendText(message);
         }
    
  5. 前端交互ws

     //web-socket
     function initSocket(){
     	var ws;
     	//检测浏览器是否支持webSocket
     	if("WebSocket" in window){
     		console.log("您的浏览器支持webSocket!"); 			
     		
     		//创建 WebSocket 对象,注意请求路径!!!!
     		ws = new WebSocket("ws://"+ ip +"/web/socket");
     		
     		//与服务端建立连接时触发
     		ws.onopen = function(){
     			 console.log("与服务端建立连接建立成功!");
     			 
     			 //模拟发送数据到服务器
     			 ws.send("你好服务端!可以开始连接传输数据了...... ");
     		}
     		
     		//接收到服务端消息时触发
     		ws.onmessage = function (evt) { 
     			let received_msg = evt.data; 
     			console.log("接收到服务端消息:"+received_msg); 
     			 
     			//获取课程信息
     			initScourse();
     		};
     		
     		//服务端关闭连接时触发
     		ws.onclose = function() { 
     			console.log("连接已经关闭.....")
     		};
     	}else{
     		console.error("您的浏览器不支持webSocket!");
     	}
     }
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值