2017-08-01 160 views
1

溝通我想建立一個應用程序,其中服務器將繼續推送消息到客戶端在一定的時間間隔。 我有一個這樣的簡單的html文件。如何與春天websocket

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> 
<script src="sockjs/sockjs.js"></script> 
<script src="stomp/stomp.js"></script> 
<div ng-app="myApp" ng-controller="myCtrl"> 
<button ng-click='connect()'>hi</button> 
</div> 

<script> 
var app = angular.module('myApp', []); 

app.controller('myCtrl', function($scope) { 
    $scope.connect = function() { 
     var socket = new SockJS('http://localhost:8099/myws'); 
     $scope.stompClient = Stomp.over(socket); 
     $scope.stompClient.connect({}, function (frame) { 
      console.log('Connected:bhabani ' + frame); 
      $scope.stompClient.subscribe('http://localhost:8099/topic/jobconfig', function (wsdata) { 
       console.log("helloooooooooooooooooooooooooooooooooooooooooooooooooo"); 
       console.log(wsdata); 
      }); 
     }); 
    } 
}); 
</script> 

我在文件系統中打開了html文件。 file:///export/data1/test-ws.html在瀏覽器中。

現在我有一個像這樣的彈簧網絡套接字。

@Configuration 
@EnableWebSocketMessageBroker 
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { 

    @Autowired 
    private GreetingController gc; 

    @Override 
    public void configureMessageBroker(MessageBrokerRegistry config) { 
     config.enableSimpleBroker("/topic"); 
     config.setApplicationDestinationPrefixes("/app"); 
    } 

    @Override 
    public void registerStompEndpoints(StompEndpointRegistry registry) { 
     registry.addEndpoint("/myws").setAllowedOrigins("*").withSockJS(); 
     new Thread(gc).start(); 
    } 

} 

有一個問候控制器這樣的,應在一些內部

@Component 
public class GreetingController implements Runnable{ 

    @Autowired 
    private SimpMessagingTemplate template; 

    public void run() { 
     try { 
      Thread.sleep(10000); 
     } catch (InterruptedException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 
     while(true){ 
     try { 
      System.out.println("Sending"); 
      Thread.sleep(1000); 
      template.convertAndSend("/topic/jobconfig", new Greeting("hi")); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     } 
    } 

如果我按下連接按鈕,我可以看到連接建立推送消息的話題。 但之後,我沒有看到任何消息來自瀏覽器應該從服務器推送。

我期待'helloooooooooooo'消息應該在每個間隔的瀏覽器控制檯中打印出來。

回答

0

將stomp客戶端訂閱代碼中的URL從此http://localhost:8099/topic/jobconfig更改爲此/topic/jobconfig

$scope.stompClient.subscribe('/topic/jobconfig', function(wsdata) { 
        console.log("hello"); 
        console.log(wsdata); 
       }); 
+0

非常感謝。有效 :) –