Skip to content

Instantly share code, notes, and snippets.

@john-nash-rs
Created May 14, 2019 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save john-nash-rs/7ac45e9ed94bd7f37669966b05e39c80 to your computer and use it in GitHub Desktop.
Save john-nash-rs/7ac45e9ed94bd7f37669966b05e39c80 to your computer and use it in GitHub Desktop.
STOMP events can be routed to @controller classes. For example, we will want methods which can be exposed to the client to add user to the chat or send message.
package com.nulpointerexception.npechatroom;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.stereotype.Controller;
import static java.lang.String.format;
@Controller
public class ChatRoomController {
private static final Logger logger = LoggerFactory.getLogger(ChatRoomController.class);
@Autowired
private SimpMessageSendingOperations messagingTemplate;
@MessageMapping("/chat/{roomId}/sendMessage")
public void sendMessage(@DestinationVariable String roomId, @Payload Message chatMessage) {
logger.info(roomId+" Chat messahe recieved is "+chatMessage.getContent());
messagingTemplate.convertAndSend(format("/chat-room/%s", roomId), chatMessage);
}
@MessageMapping("/chat/{roomId}/addUser")
public void addUser(@DestinationVariable String roomId, @Payload Message chatMessage,
SimpMessageHeaderAccessor headerAccessor) {
String currentRoomId = (String) headerAccessor.getSessionAttributes().put("room_id", roomId);
if (currentRoomId != null) {
Message leaveMessage = new Message();
leaveMessage.setType(Message.MessageType.LEAVE);
leaveMessage.setSender(chatMessage.getSender());
messagingTemplate.convertAndSend(format("/chat-room/%s", currentRoomId), leaveMessage);
}
headerAccessor.getSessionAttributes().put("name", chatMessage.getSender());
messagingTemplate.convertAndSend(format("/chat-room/%s", roomId), chatMessage);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment