I'm developing a web application using spring boot, angular cli and sockjs.
WebSocket implementation:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/info", "/user", "/notif");
registry.setApplicationDestinationPrefixes("/app");
}
}
Angular websocket util implementation:
Note: This class is used to connect web socket and subscribe routines!
@Injectable()
export class WebSocketUtil {
stompClient = null;
constructor() {
}
connect(subscribers: Subscriber[] = null) {
let _this = this;
let socket = new SockJS("https://localhost/ws");
if (socket != null) {
this.stompClient = Stomp.over(socket);
if (this.stompClient != null) {
console.log("Stomp client is connected!");
let headers = {};
headers["X-CSRF-TOKEN"] = ...;// csrf code
this.stompClient.connect(headers, (frame) => {
subscribers.forEach((subscriber) => {
_this.stompClient.subscribe(subscriber.URL, subscriber.CALLBACK);
});
}, () => {
console.log(_this.stompClient);
});
} else {
throw {
name: "StompClientNotRegistered",
message: "Stomp client is not registered!"
};
}
} else {
throw {
name: "SocketEstablishFailed",
message: "Socket cannot be established!"
};
}
}
send(message) {
this.stompClient.send(message.url, JSON.stringify(message.params));
}
}
Angular subscriber class implementation:
Note: This class is used to bind subscribe routines to stomp client!
export class Subscriber {
constructor(private url: string = "", private callback: any) {
}
get URL() {
return this.url;
}
get CALLBACK() {
return this.callback;
}
}
WebsocketUtil usage:
Note: This snippet of code is called after view init stage.
this.webSocketUtil.connect([
new Subscriber("/notif", function (data) {
console.log(data);
}),
new Subscriber("/user", function (data) {
console.log(data);
})
]);
The code above causes following error in web browser(both FF & chrome) console:
Note: https://localhost/ws is accessible and returns "Welcome to SockJS!" message.
