【问题标题】:Multiple rooms in Spring using STOMPSpring 中使用 STOMP 的多个房间
【发布时间】:2015-04-07 20:35:09
【问题描述】:

是否可以使用 STOMP 和 Spring 4 创建房间? Socket.IO内置了房间,所以我想知道Spring是否有这个

我现在的代码:

@MessageMapping("/room/greet/{room}")
@SendTo("/room/{room}")
public Greeting greet(@DestinationVariable String room, HelloMessage message) throws Exception {
    return new Greeting("Hello, " + room + "!");
}

最好有@SendTo("/room/{room}")

但是,我仅限于:

@SendTo("/room/room1") 
@SendTo("/room/room2")
@SendTo("/room/room3") 

等等......这是非常非常不理想的

客户是:

stompClient.subscribe('/room/' + roomID, function(greeting){
    showGreeting(JSON.parse(greeting.body).content);
});

其中 roomID 可以是 room1、room2 或 room3... 如果我想要更多房间怎么办?现在感觉好痛

【问题讨论】:

    标签: spring websocket stomp spring-websocket


    【解决方案1】:

    看起来这个“房间”功能实际上是一种发布/订阅机制,是通过 Spring Websocket 支持中的主题实现的(有关更多信息,请参阅 STOMP protocol support and destinations)。

    用这个例子:

    @Controller
    public class GreetingController {
    
      @MessageMapping("/room/greeting/{room}")
      public Greeting greet(@DestinationVariable String room, HelloMessage message) throws Exception {
        return new Greeting("Hello, " + message.getName() + "!");
      }
    
    }
    

    如果消息发送到“/room/greeting/room1”,那么Greeting的返回值会自动发送到“/topic/room/greeting/room1”,所以初始目的地以“/topic”为前缀。

    如果你想自定义目的地,你可以像以前一样使用@SendTo,或者像这样使用MessagingTemplate:

    @Controller
    public class GreetingController {
    
      private SimpMessagingTemplate template;
    
      @Autowired
      public GreetingController(SimpMessagingTemplate template) {
        this.template = template;
      }
    
      @MessageMapping("/room/greeting/{room}")
      public Greeting greet(@DestinationVariable String room, HelloMessage message) throws Exception {
        Greeting greeting = new Greeting("Hello, " + message.getName() + "!");
        this.template.convertAndSend("/topic/room/"+room, greeting);  
      }
    
    }
    

    我认为快速浏览一下the reference documentation 和一些有用的示例,例如portfolio appchat app 应该很有用。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2020-10-23
    • 2014-07-18
    • 1970-01-01
    相关资源
    最近更新 更多