我正在扩展此git'let项目以发送/接收私人消息 - 仅针对特定订阅用户。我可以发送它,但订阅者没有收到它们。我添加了分叉的完整代码here,下面是代码的重要部分的片段。
配置:
@Configuration
@EnableScheduling
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Autowired
private SessionBasedHandshakeHandler handshakeHandler;
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic", "/queue");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/gs-guide-websocket").setHandshakeHandler(handshakeHandler).withSockJS();
}
}
控制器:
@Controller
public class GreetingController {
@Autowired
public SimpMessageSendingOperations messagingTemplate;
private Set<String> users = new HashSet<>();
@GetMapping("/subscribe4PrivateMsgs")
public @ResponseBody String enablePrivateMessages(HttpSession session) {
String sessionId = session.getId();
users.add(sessionId);
return sessionId;
}
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
Thread.sleep(1000); // simulated delay
return new Greeting("Hello, " + message.getName() + "!");
}
@Scheduled(fixedDelay = 5000)
private void sendPrivateMessageToScubscribers() {
users.forEach((sessionId) -> {
SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
headerAccessor.setSessionId(sessionId);
headerAccessor.setLeaveMutable(true);
String msg = sessionId + ":" + GregorianCalendar.getInstance().getTimeInMillis();
Greeting response = new Greeting(msg);
//Tried the following to Send Private Message, but it doens't works
messagingTemplate.convertAndSendToUser(sessionId, "/queue/private", response,
headerAccessor.getMessageHeaders());
//The following reached UI successfully - but to all users
/*response.setContent("Public Msg:: " + msg);
messagingTemplate.convertAndSend("/topic/greetings", response);*/
});
}
}
UI:
function connect() {
$.get("/subscribe4PrivateMsgs", function(userId) {
var socket = new SockJS('/gs-guide-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function (greeting) {
showGreeting('Received Public Msg: ' + JSON.parse(greeting.body).content);
});
stompClient.subscribe('/user/queue/private', function (greeting) {
showGreeting('1 Received Private Msg: ' + JSON.parse(greeting.body).content);
});
stompClient.subscribe('/user/'+userId+'/queue/private', function (greeting) {
showGreeting('2 Received Private Msg: ' + JSON.parse(greeting.body).content);
});
});
});
}
答案 0 :(得分:0)
原来这条线路造成了问题。
messagingTemplate.convertAndSendToUser(sessionId, "/queue/private", response, headerAccessor.getMessageHeaders());
将其更改为
messagingTemplate.convertAndSendToUser(sessionId, "/queue/private", response);
解决了这个问题。 Github更新了工作副本。