繁体   English   中英

Spring脚踩-使用SimpMessagingTemplate从服务器发送消息

[英]Spring stomp - send a message from server using SimpMessagingTemplate

我正在尝试使用stomp从服务器向客户端发送消息。 我知道在客户端使用sock.js和stomp可以通过一个控制器方法简单地使用@SendTo注释,将一个用户的消息发送给另一个用户,而无需太多服务器端的交互。 但是,我希望用户接收的消息是在服务器上生成的(实际上,我正在发送整个对象,但是为了简单起见,我们只是说我正在尝试发送String)。 具体而言,这涉及接受好友请求,并且当一个用户接受好友请求时,发送请求的用户应该收到一条消息,表明他的请求已被接受。 因此,在通过简单的ajax调用rest控制器方法来接受请求之后,该方法还应该将消息发送给其他用户。 这是代码:

@RestController
@RequestMapping("/rest/user")
public class UserController{
    @Autowired
    SimpMessagingTemplate simp;

    @RequestMapping(value="/acceptFriendRequest/{id}", method=RequestMethod.GET, produces = "application/json")
    public boolean acceptFriendRequest(@PathVariable("id") int id){
        UserDTO user = getUser(); // gets logged in user
        if (user == null)
            return false;
        ... // Accept friend request, write in database, etc.
        String username = ... // gets the username from a service, works fine
        simp.convertAndSendToUser(username, "/project_sjs/notify/acceptNotification", "Some processed text!");
        return true;
    }
}

这是Web套接字配置:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/sendNotification").withSockJS();

    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {

        config.enableSimpleBroker("/notify");
        config.setApplicationDestinationPrefixes("/project_sjs");
    }


}

这是javascript函数:

function setupWebsockets(){
    var socketClient = new SockJS("/project_sjs/sendNotification");
    stompClient = Stomp.over(socketClient);
    stompClient.connect({}, function(frame){
        stompClient.subscribe("/project_sjs/notify/acceptNotification", function(retVal){
            console.log(retVal);
        });
    });
}

当用户接受好友请求时,数据库中的所有内容都将正确写入。 刷新页面时,我什至可以看到另一个用户现在是我的朋友。 但是,其他用户永远不会收到该请求被接受的消息。 我做错了什么吗? 任何帮助将不胜感激。 谢谢!

我用另一种方法解决了这个问题。 我没有将所有用户都预订到相同的端点“ / project_sjs / notify / acceptNotification”,然后通过用户名对其进行区分,而是最终将每个用户都预订到了不同的端点,例如“ / project_sjs / notify / acceptNotification / John123”。 这样,具有用户名John123(这是一个人,因为用户名是唯一的)的每个人都将收到通知。 而且效果很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM