Вот конфигурация WebSocket на сервере загрузки Java Spring:< /p>
Код: Выделить всё
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic", "/queue");
config.setApplicationDestinationPrefixes("/app");
config.setUserDestinationPrefix("/user");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/notifications")
.setAllowedOrigins("http://localhost:3000") // Allow frontend origin
.withSockJS();
}
}
@Service
public class NotificationService {
private final SimpMessagingTemplate messagingTemplate;
@Autowired
public NotificationService(SimpMessagingTemplate messagingTemplate) {
this.rabbitTemplate = rabbitTemplate;
this.messagingTemplate = messagingTemplate;
}
public void sendWelcomeNotification(UserEntity loggedInUser) {
// Notification data
String message = "Welcome to HydroLife, " + loggedInUser.getName() + "!";
String sender = "HydroLife";
LocalDateTime timestamp = LocalDateTime.now();
String profileImage = "/images/Logo3.png";
var notification = new NotificationDTO(sender, message, timestamp, profileImage);
/// Sending the notification via WebSocket to the frontend
// Converting and sending to the specific user destination
messagingTemplate.convertAndSendToUser(
loggedInUser.getEmail(),
"/queue/notifications",
notification
);
}
}
Код: Выделить всё
useEffect(() =\> {
const socket = new SockJS('http://localhost:8080/notifications');
const stompClient = new Client({
onConnect: () =\> {
console.log('Connected to WebSocket');
stompClient.subscribe('/user/queue/notifications', (message) => {
const notificationData = JSON.parse(message.body);
setNotification(notificationData);
console.log('New notification received:', notificationData);
});
},
});
stompClient.activate();
return () => {
if (stompClient) {
stompClient.deactivate();
console.log('Disconnected from WebSocket');
}
};
}, []);
Я уже проверил, отправляет ли сервер сообщения, и вроде работает правильно. Почему мой клиент React с Next.js не получает сообщения от WebSocket на бэкэнде Spring Boot? Может быть, мне что-то не хватает или какая-то неправильная конфигурация в соединении WebSocket?
Подробнее здесь: https://stackoverflow.com/questions/790 ... -websocket