Reputation:
I am trying to build an application where the server will keep pushing message to the client in some interval. I have a simple html file like this.
<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>
I opened the html file in the file system. file:///export/data1/test-ws.html in the browser.
Now i have a spring web socket like this.
@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();
}
}
Have a greeting controller like this, which should push a message to the topic in some internal
@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();
}
}
}
Where i press the connect button i can see connection is established. But after that i do not see any message coming in the browser which should be pushed from the server.
I am expecting the 'helloooooooooooo' message should be printed in my browser console in each interval.
Upvotes: 1
Views: 385
Reputation: 4084
Change URL in stomp client subscribe code from this http://localhost:8099/topic/jobconfig
to this /topic/jobconfig
.
$scope.stompClient.subscribe('/topic/jobconfig', function(wsdata) {
console.log("hello");
console.log(wsdata);
});
Upvotes: 1