如何仅从服务器向特定用户发送websocket消息?
我的webapp具有弹簧安全设置并使用websocket.我遇到了一个棘手的问题,试图只从服务器向特定用户发送消息.
我阅读本手册的理解来自我们可以做的服务器
simpMessagingTemplate.convertAndSend("/user/{username}/reply", reply);
Run Code Online (Sandbox Code Playgroud)
在客户端:
stompClient.subscribe('/user/reply', handler);
Run Code Online (Sandbox Code Playgroud)
但我永远无法调用订阅回调.我尝试了许多不同的路径,但没有运气.
如果我将它发送到/ topic/reply它可以工作,但所有其他连接的用户也会收到它.
为了说明问题,我在github上创建了这个小项目:https://github.com/gerrytan/wsproblem
重现步骤:
1)克隆并构建项目(确保您使用的是jdk 1.7和maven 3.1)
$ git clone https://github.com/gerrytan/wsproblem.git
$ cd wsproblem
$ mvn jetty:run
Run Code Online (Sandbox Code Playgroud)
2)导航到http://localhost:8080,使用bob/test或jim/test登录
3)单击"请求用户特定消息".预期:仅对此用户的"仅收到消息给我"旁边显示消息"hello {username}",实际:未收到任何消息
我一直在努力用Spring-Security 正确实现Stomp(websocket)身份验证和授权.对于后代,我会回答我自己的问题,提供指导.
Spring WebSocket文档(用于身份验证)看起来不清楚ATM(恕我直言).我无法理解如何正确处理身份验证和授权.
Principal在控制器可用.在我的应用程序中,我需要向特定用户发送实时通知。我的WebSocketConfig课如下,
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
stompEndpointRegistry.addEndpoint("/websocket-example")
.withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
}
}
Run Code Online (Sandbox Code Playgroud)
大多数时候信息会由服务器端发送。所以我还没有设置应用程序目的地。
在客户端,我订阅了目标“/topic/user”,
function connect() {
var socket = new SockJS('/websocket-example');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/user', function (greeting) {
// showGreeting(JSON.parse(greeting.body).content);
console.log("Received message through WS");
});
});
}
Run Code Online (Sandbox Code Playgroud)
在RestController我的一个方法中,我有一种方法可以将消息广播给所有连接的客户端。
@GetMapping("/test")
public void test()
{
template.convertAndSend("/topic/user", "Hurray");
}
Run Code Online (Sandbox Code Playgroud)
直到这部分一切正常。我收到消息并正在登录到控制台。
现在,如果我只想将通知发送给特定用户,则必须使用template.convertAndSendToUser(String user, String …