春季启动,WebSocket 不会向指定用户发送通知



我在向指定用户发送通知时遇到了这样的问题。这是我的配置文件。

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.setApplicationDestinationPrefixes("/app");
//registry.enableSimpleBroker("/topic");
}

这是我的客户代码

$(document).ready(function () {
connect();

}

function connect() {
var socket = new SockJS('/ws');
stompClient = Stomp.over(socket);
stompClient.connect({}, function () {
stompClient.subscribe("/user/queue/reply", function (notification) {
console.log("------------------------ subscribed !!!!!!");
notify(JSON.parse(notification.body).content);
});
});

}

该控制器处理所有与聊天相关的处理程序方法

@MessageMapping("/message")
@SendToUser("/queue/reply")
public ChatMessage processMessageFromClient(@Payload ChatMessage chatMessage) throws Exception {
return chatMessage;
}

伙计们,我似乎是Spring启动websocket领域的新手,请告诉我这是否足以向指定用户发送通知。相反,当我执行前面提到的客户端代码时,得到通知的是我,用户主体,而不是所需的用户。我做错了什么?它说,spring-boot将会话id隐藏起来,并用它来决定发送通知的人。但这里的情况似乎并非如此。。。

这是单击通知发送按钮时的浏览器日志。

Opening Web Socket...
stomp.min.js:8 Web Socket Opened...
stomp.min.js:8 >>> CONNECT
accept-version:1.1,1.0
heart-beat:10000,10000
stomp.min.js:8 <<< CONNECTED
version:1.1
heart-beat:0,0
user-name:hmkhitaryan
stomp.min.js:8 connected to server undefined
stomp.min.js:8 >>> SUBSCRIBE
id:sub-0
destination:/user/queue/reply
stomp.min.js:8 >>> SEND
destination:/app/message
content-length:71
{"sender":"hmkhitaryan","content":"friend request","type":"FR_REQUEST"}
stomp.min.js:8 <<< MESSAGE
destination:/user/queue/reply
content-type:application/json;charset=UTF-8
subscription:sub-0
message-id:xgec4kaf-15
content-length:71
{"type":"FR_REQUEST","content":"friend request","sender":"hmkhitaryan"}

问题是,它没有发送下一个用户"hmkhitaryan1",而是发送给我"hmkhitaryan"。

您可以使用convertandSend回复特定用户。像这样-

@Controller
public class GreetingController {
@Autowired
private SimpMessageSendingOperations  template ;

@MessageMapping("/message")
public void greeting(@Payload String message, 
Principal principal){
template.convertAndSendToUser(<userName_youwant_tosend>,"/queue/queue1",message);
}
}

并且在您的配置类-中

@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic","/queue","/user");
config.setApplicationDestinationPrefixes("/app");
config.setUserDestinationPrefix("/user");
}

我在sendToUser中也遇到了同样的问题。但这对我很管用。希望能有所帮助。

最新更新