I am trying to connect the frontend to the backend using websockets with compatclient but the web server displays the above error when inspecting. i have tried to fix it but nothing seems to be working.
The connection is to a form that takes 4 parameters and passes it to the database. The data is stored in the database properly when I used Postman.
connect.service.ts:17 WebSocket connection to 'ws://localhost:9000/ws' failed:
is shown in the web browser when inspecting.
The code files are shown below.
This is my Web socket Configuration class
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic", "/queue"); // destination prefix for receiving messages
config.setApplicationDestinationPrefixes("/app"); // prefix for sending messages
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// Register the WebSocket endpoint
registry.addEndpoint("/ws").setAllowedOrigins("http://localhost:4200/").withSockJS();
}
}
This is the Controller class for the websocket
package com.example.Coursework1_BE.WebSocket;
import com.example.Coursework1_BE.Configuration;
import java.util.Map;
import com.example.Coursework1_BE.Repositories.ConfigurationRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class WSController {
@Autowired
private ConfigurationRepo configurationRepo;
@GetMapping("/configuration")
@SendTo("/topic/config")
public Configuration saveConfig( Configuration config){
return configurationRepo.save(config);
}
}
This is the service file
import { Injectable } from '@angular/core';
import { CompatClient, Stomp, Frame } from '@stomp/stompjs';
@Injectable({
providedIn: 'root',
})
export class WebSocketService {
private stompClient: CompatClient | null = null;
constructor() {}
initWebSocket(): void {
// Create a native WebSocket endpoint
const ws = new WebSocket('ws://localhost:9000/ws');
// Initialize CompatClient using native WebSocket
this.stompClient = Stomp.over(ws);
// Disable debugging (optional, for cleaner logs)
this.stompClient.debug = () => {};
// Connect and configure the CompatClient
this.stompClient.connect(
{}, // headers
(frame: Frame) => {
console.log('Connected: ' + frame);
// Subscribe to a topic
this.stompClient?.subscribe('/topic/updates', (message) => {
console.log('Received message:', message.body);
});
},
(error: any) => {
console.error('STOMP error:', error);
}
);
}
sendMessage(destination: string, message: any): void {
if (this.stompClient && this.stompClient.connected) {
this.stompClient.send(destination, {}, JSON.stringify(message));
} else {
console.error('STOMP client is not connected.');
}
}
disconnect(): void {
if (this.stompClient && this.stompClient.connected) {
this.stompClient.disconnect(() => {
console.log('Disconnected');
});
}
}
}
and this is the component file
import { Component, OnInit } from '@angular/core';
import { WebSocketService } from '../services/connect.service';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-configuration-form',
templateUrl: './configuration-form.component.html',
styleUrls: ['./configuration-form.component.css'],
standalone: true,
imports:[FormsModule, CommonModule]
})
export class ConfigurationFormComponent implements OnInit {
data = {
totaltickets: '',
ticketreleaserate: '',
customerretrievalrate: '',
maxcapacity: '',
};
constructor(private websocketService: WebSocketService) {}
ngOnInit(): void {
// Initialize WebSocket connection
this.websocketService.initWebSocket();
}
submitForm(): void {
if (this.isValidForm()) {
this.websocketService.sendMessage('/app/config', this.data);
console.log('Form submitted:', this.data);
} else {
console.error('Form is invalid. Please fill all fields.');
}
}
isValidForm(): boolean {
return (
this.data.totaltickets.trim() !== '' &&
this.data.ticketreleaserate.trim() !== '' &&
this.data.customerretrievalrate.trim() !== '' &&
this.data.maxcapacity.trim() !== ''
);
}
}