我从Springboot开始使用Websocket。因此对于客户端,我正在使用webstomp-client library.。
要连接到websocket服务器,该库提供了connect方法,该方法还接受成功回调函数。我面临的问题是未调用回调函数。
成功建立连接后,我需要订阅队列,因此调用成功回调对于调用订阅很重要。
//controller.js
//Main Controller
clentModule.controller('clentController', function($scope) {
var client;
$scope.connectAndSubscribe = function()
{
var url = "ws://localhost:8080/gs-guide-websocket/websocket";
client = webstomp.client(url);
connected = function()
{
console.log("connected");
}
var headers = {};
client.connect(headers,function(){
console.log("successfuly connected");
var subscription = client.subscribe("/topic/greetings",subscriptionCallback);
});
subscriptionCallback = function(data) {
console.log("subscription data", data);
}
//var subscription = client.subscribe("/topic/greetings",subscriptionCallback);
//console.log(subscription);
};
$scope.sendMessage = function()
{
$scope.message = {};
$scope.message.sender = "xyz";
$scope.message.reciever = "abc";
var sendObject = JSON.stringify($scope.message);
client.send("/topic/greetings", {priority: 9}, sendObject);
};
});
//Webscocketconfig.java
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer
{
@Override
public void configureMessageBroker( MessageBrokerRegistry config )
{
config.enableSimpleBroker( "/topic" );
config.setApplicationDestinationPrefixes( "/app" );
}
@Override
public void registerStompEndpoints( StompEndpointRegistry registry )
{
registry.addEndpoint( "/gs-guide-websocket" ).setAllowedOrigins( "*" ).withSockJS();
}
}