我使用Spring和WebSockets实现了一个控制台应用程序。如果一个或多个参与者连接到像这样的anotated的基本方法,该应用程序可以正常工作。
@MessageMapping("/chat")
@SendTo("/topic/messages")
我将复制配置和我所做的实现更清楚。
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
}
@Controller
public class ChatController {
@MessageMapping("/chat")
@SendTo("/topic/messages")
public OutputMessage send(@Payload Message message) {
return new OutputMessage(message.getFrom(), message.getText());
}
@MessageMapping("/chat/{room}")
@SendTo("/topic/messages/{room}")
public OutputMessage enableChatRooms(@DestinationVariable String room, @Payload Message message) {
return new OutputMessage(message.getFrom(), message.getText());
}
}
@Service
public class SessionHandlerService extends StompSessionHandlerAdapter {
private String nickName;
public SessionHandlerService() {
this.nickName = "user";
}
private void sendJsonMessage(StompSession session) {
ClientMessage msg = new ClientMessage(nickName, " new user has logged in.");
session.send("/app/chat", msg);
}
@Override
public Type getPayloadType(StompHeaders headers) {
return ServerMessage.class;
}
@Override
public void handleFrame(StompHeaders headers, Object payload) {
System.err.println(payload.toString());
}
@Override
public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
session.subscribe("/topic/messages", new SessionHandlerService());
sendJsonMessage(session);
}
}
我面临的问题是,当我订阅/topic/messages
和session.send("/app/chat", msg);
时,一切正常。但是,如果我选择session.send("/app/chat/room1", msg);
和/topic/messages/room1
之类的内容,参与者就无法看到彼此的消息,就像他们在不同的聊天室中一样。