I have a project in a vpn and I try to create a chat with a socket using WebSocket. This is the controller:
@MessageMapping("/chat.send")
@SendTo("/topic/public")
public ChatMessage sendMessage (@Payload ChatMessage chatMessage){
return chatMessage;
}
@MessageMapping("/chat.newUser")
@SendTo("/topic/public")
public ChatMessage newUser(@Payload ChatMessage chatMessage,
SimpMessageHeaderAccessor headerAccessor) {
// Add username in web socket session
headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
return chatMessage;
}
This is the listener:
private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketEventListener.class);
@Autowired
private SimpMessageSendingOperations sendingOperations;
@EventListener
public void handleWebSocketConnectListener (final SessionConnectedEvent event){
LOGGER.info("Se creo una nueva conexion chat");
/*final StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
final String username = (String) headerAccessor.getSessionAttributes().get("username");
final ChatMessage chatMessage = ChatMessage.builder()
.type(MessageType.CONNECT)
.sender(username)
.build();
sendingOperations.convertAndSend("/topic/public", chatMessage);*/
}
@EventListener
public void handleWebSocketDisconnectListener (final SessionDisconnectEvent event) {
final StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
final String username = (String) headerAccessor.getSessionAttributes().get("username");
final ChatMessage chatMessage = ChatMessage.builder()
.type(MessageType.DISCONNECT)
.sender(username)
.build();
sendingOperations.convertAndSend("/topic/public", chatMessage);
}
and this one the config:
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.setApplicationDestinationPrefixes("/app");
config.enableSimpleBroker("/topic"); //deberia cambiarse por el enableStompBroker
/*
config.enableStompBrokerRelay("/topic")
.setRelayHost("localhost")
.setRelayPort(61613)
.setClientLogin("guest")
.setClientPasscode("guest");
*/
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat").withSockJS();
}
the parts commented on I left them like that because I was looking at how to solve the issue.
Now, the client connects by vpn using angle and socketjs. This is the code in angular
export class WebSocketAPIService {
private webSocketEndPoint: string = environment.baseurl + '/chat.newUser';
private topic = '/topic/public';
private stompClient: Stomp.Client;
public mensajeRecibidoEmitter: EventEmitter<Message> = new EventEmitter<Message>();
constructor() { }
public _connect(): void {
console.log('Initialize WebSocket Connection');
const ws = new SockJS(this.webSocketEndPoint);
this.stompClient = Stomp.over(ws);
this.stompClient.connect({}, (frame: Frame) => {
this.stompClient.subscribe(this.topic, (sdkEvent: Message) => {
this.onMessageReceived(sdkEvent);
});
// _this.stompClient.reconnect_delay = 2000;
}, (err) => this.errorCallBack(err));
}
public _disconnect(): void {
if (this.stompClient !== null) {
this.stompClient.disconnect(() => {
console.log('Disconnected');
});
}
}
// on error, schedule a reconnection attempt
errorCallBack(error) {
console.log('errorCallBack -> ' + error);
setTimeout(() => {
// this._connect();
console.log(' trying reconnect...');
}, 5000);
}
_send(message) {
console.log('calling logout api via web socket');
this.stompClient.send('/app/hello', {}, JSON.stringify(message));
}
onMessageReceived(message: Message): void {
console.log('Message Recieved from Server :: ' + message);
// this.appComponent.handleMessage(JSON.stringify(message.body));
this.mensajeRecibidoEmitter.emit(message);
}
}
and throw this error:
Access to XMLHttpRequest at 'http://192.168.100.71:8080/dpo_backend_dev/chat.newUser/info?t=1603389915235' from origin 'http://localhost:4200' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
I don't know how to solve it since I'm learning to use webSocket but for some reason I only listen to what happens in localhosty not connecting between vpn. Any help?