@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer{
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.setAllowedOrigins("https://nighthawkcoders.github.io", "https://cj-backend.stu.nighthawkcodingsociety.com","http://localhost:4000", "https://toby-leeder.github.io", "https://classroomjukebox.com/")
.withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry){
registry.setApplicationDestinationPrefixes("/app");
registry.enableSimpleBroker("/topic");
}
}
Creating the SockJS endpoint. Also creates a the configureMessageBroker method, which is used later. /app is how you connect pretty much, and /topic is the endpoint used for messages.
@Component
@RequiredArgsConstructor
@Slf4j
public class WebSocketEventListener {
private final SimpMessageSendingOperations messageTemplate;
@EventListener
public void handleWebSocletDisconnectListener(SessionDisconnectEvent event){
StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
String username = (String) headerAccessor.getSessionAttributes().get("username");
if (username != null){
log.info("User disconnected: {}", username);
var chatMessage = ChatMessage.builder()
.type(MessageType.LEAVE)
.sender(username)
.build();
messageTemplate.convertAndSend("/topic/public", chatMessage);
}
}
}
@Controller
public class ChatController {
@MessageMapping("/chat.sendMessage")
@SendTo("/topic/public")
public ChatMessage sendMessage(@Payload ChatMessage chatMessage){
return chatMessage;
}
@MessageMapping("/chat.addUser")
@SendTo("/topic/public")
public ChatMessage addUser(@Payload ChatMessage chatMessage, SimpMessageHeaderAccessor headerAccessor){
// Add username in web socket session
headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
return chatMessage;
}
}