Viego
Viego
Explore posts from servers
KPCKevin Powell - Community
Created by Viego on 6/10/2024 in #back-end
WebSocket Chat Application in Spring Boot Not Receiving Messages in Postman
@Component
public class TradeWebSocketHandler extends TextWebSocketHandler {

private final Map<Long, WebSocketSession> sessions = new HashMap<>();
private final ObjectMapper objectMapper = new ObjectMapper();

@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
Long matricule = (Long) session.getAttributes().get("matricule");
sessions.put(matricule, session);
System.out.println("Connected: " + matricule);
}

@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String payload = message.getPayload();
System.out.println("Received: " + payload);

// Parse the message
ChatMessageDTO chatMessageDTO = objectMapper.readValue(payload, ChatMessageDTO.class);

// Get the recipient's session
WebSocketSession recipientSession = sessions.get(chatMessageDTO.recipientId());
if (recipientSession != null && recipientSession.isOpen()) {
recipientSession.sendMessage(new TextMessage(payload));
}
}

@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
Long matricule = (Long) session.getAttributes().get("matricule");
sessions.remove(matricule);
System.out.println("Disconnected: " + matricule);
}
}
@Component
public class TradeWebSocketHandler extends TextWebSocketHandler {

private final Map<Long, WebSocketSession> sessions = new HashMap<>();
private final ObjectMapper objectMapper = new ObjectMapper();

@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
Long matricule = (Long) session.getAttributes().get("matricule");
sessions.put(matricule, session);
System.out.println("Connected: " + matricule);
}

@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String payload = message.getPayload();
System.out.println("Received: " + payload);

// Parse the message
ChatMessageDTO chatMessageDTO = objectMapper.readValue(payload, ChatMessageDTO.class);

// Get the recipient's session
WebSocketSession recipientSession = sessions.get(chatMessageDTO.recipientId());
if (recipientSession != null && recipientSession.isOpen()) {
recipientSession.sendMessage(new TextMessage(payload));
}
}

@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
Long matricule = (Long) session.getAttributes().get("matricule");
sessions.remove(matricule);
System.out.println("Disconnected: " + matricule);
}
}
Chat Controller:
@RestController
@RequestMapping("/api/chat")
public class ChatController {

@Autowired
private SimpMessagingTemplate messagingTemplate;

@Autowired
private ChatService chatService;

@MessageMapping("/chat.sendMessage")
public void sendMessage(@DestinationVariable Long matricule, ChatMessageDTO chatMessageDTO) {
ChatMessageDTO updatedChatMessageDTO = new ChatMessageDTO(
null,
chatMessageDTO.senderId(),
chatMessageDTO.recipientId(),
chatMessageDTO.content(),
LocalDateTime.now(),
chatMessageDTO.isPrivate()
);

ChatMessageDTO savedChatMessageDTO = chatService.saveMessage(updatedChatMessageDTO);
System.out.println("Saved ChatMessageDTO: " + savedChatMessageDTO);

try {
messagingTemplate.convertAndSendToUser(
savedChatMessageDTO.recipientId().toString(),
"/queue/messages",
savedChatMessageDTO
);
System.out.println("Message sent to user: " + savedChatMessageDTO.recipientId());
} catch (Exception e) {
System.err.println("Error sending message: " + e.getMessage());
}
}

@GetMapping("/history")
public ResponseEntity<List<ChatMessageDTO>> getChatHistory(@RequestParam Long senderId, @RequestParam Long recipientId) {
List<ChatMessageDTO> messages = chatService.getChatHistory(senderId, recipientId);
return ResponseEntity.ok(messages);
}

@GetMapping("/unique-conversations")
public ResponseEntity<List<Long>> getUniqueConversations(@RequestParam Long userMatricule) {
List<Long> conversations = chatService.getUniqueConversations(userMatricule);
return ResponseEntity.ok(conversations);
}
}
@RestController
@RequestMapping("/api/chat")
public class ChatController {

@Autowired
private SimpMessagingTemplate messagingTemplate;

@Autowired
private ChatService chatService;

@MessageMapping("/chat.sendMessage")
public void sendMessage(@DestinationVariable Long matricule, ChatMessageDTO chatMessageDTO) {
ChatMessageDTO updatedChatMessageDTO = new ChatMessageDTO(
null,
chatMessageDTO.senderId(),
chatMessageDTO.recipientId(),
chatMessageDTO.content(),
LocalDateTime.now(),
chatMessageDTO.isPrivate()
);

ChatMessageDTO savedChatMessageDTO = chatService.saveMessage(updatedChatMessageDTO);
System.out.println("Saved ChatMessageDTO: " + savedChatMessageDTO);

try {
messagingTemplate.convertAndSendToUser(
savedChatMessageDTO.recipientId().toString(),
"/queue/messages",
savedChatMessageDTO
);
System.out.println("Message sent to user: " + savedChatMessageDTO.recipientId());
} catch (Exception e) {
System.err.println("Error sending message: " + e.getMessage());
}
}

@GetMapping("/history")
public ResponseEntity<List<ChatMessageDTO>> getChatHistory(@RequestParam Long senderId, @RequestParam Long recipientId) {
List<ChatMessageDTO> messages = chatService.getChatHistory(senderId, recipientId);
return ResponseEntity.ok(messages);
}

@GetMapping("/unique-conversations")
public ResponseEntity<List<Long>> getUniqueConversations(@RequestParam Long userMatricule) {
List<Long> conversations = chatService.getUniqueConversations(userMatricule);
return ResponseEntity.ok(conversations);
}
}
Why am I not receiving messages in the recipient WebSocket session? Is there a mistake in my WebSocket or STOMP configuration? Are there any specific settings in Postman that I need to adjust for testing WebSocket communication? Is my sendMessage method correctly set up to handle and route messages via STOMP? Any insights or suggestions to resolve this issue would be greatly appreciated. Thank you!
2 replies
KPCKevin Powell - Community
Created by Viego on 6/10/2024 in #front-end
Real-time Chat Messages Not Appearing in Angular & Spring Boot Application
No description
5 replies
KPCKevin Powell - Community
Created by Viego on 6/10/2024 in #front-end
Real-time Chat Messages Not Appearing in Angular & Spring Boot Application
No description
5 replies
KPCKevin Powell - Community
Created by Viego on 6/10/2024 in #front-end
Real-time Chat Messages Not Appearing in Angular & Spring Boot Application
5 replies
KPCKevin Powell - Community
Created by Viego on 6/10/2024 in #front-end
Real-time Chat Messages Not Appearing in Angular & Spring Boot Application
5 replies