如何使用Spring 4在我的webSocket服务器中捕获订阅事件 [英] how to capture subscribe event in my webSocket server with Spring 4

查看:313
本文介绍了如何使用Spring 4在我的webSocket服务器中捕获订阅事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用spring 4,STOMP和sock.js进行了简单的Web套接字通信,遵循此 https:/ /spring.io/guides/gs/messaging-stomp-websocket/

I did a simple web socket communication with spring 4, STOMP and sock.js, following this https://spring.io/guides/gs/messaging-stomp-websocket/

现在我想将其升级为简单聊天。我的问题是,当用户订阅新的聊天室时,他应该过去的消息。我不知道如何捕捉他订阅时向他发送消息列表的那一刻。

Now I want to upgrade it to simple chat. My problem is that when user subscribes to new chat room, he should get past messages. I don't know how to capture the moment when he subscribed to send him the list of the messages.

我尝试使用@MessageMapping注释,但没有达到任何成功:

I tried using @MessageMapping annotation, but didn't reach any success:

@Controller
public class WebSocketController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;


    @MessageMapping("/chat/{chatId}")
    public void chat(ChatMessage message, @DestinationVariable String chatId) {
        messagingTemplate.convertAndSend("/chat/" + chatId, new ChatMessage("message: " + message.getText()));
    }

    @SubscribeMapping("/chat")
    public void chatInit() {
        System.out.println("worked");
        int chatId = 1; //for example
        messagingTemplate.convertAndSend("/chat/" + chatId, new ChatMessage("connected"));
    }

}

然后我创建了:

@Controller
public class ApplicationEventObserverController implements ApplicationListener<ApplicationEvent> {
    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        System.out.println(applicationEvent);
    }
}

它有效但捕获所有可能的事件,我不知道我认为这是一个很好的做法。

It works, but captures all possible events, I don't think it is a good practice.

所以,我的问题可以改写:如何在用户提交给某些人时发送初始数据?

So, my question can be rephrased: how to send initial data when user subscried to sth?

推荐答案

当使用 @SubscribeMapping 处理程序订阅目标时,您可以将任何内容直接返回给客户端方法。返回的对象不会转到代理,而是直接发送给客户:

You can return anything directly to a client when it subscribes to a destination using a @SubscribeMapping handler method. The returned object won't go to the broker but will be sent directly to the client:

@SubscribeMapping("/chat")
public Collection<ChatMessage> chatInit() {
    ...
    return messages;
}

在客户端:

socket.subscribe("/app/chat", function(message) {
    ...
});

查看聊天示例,显示了这个确切的场景。

Check out the chat example on GitHub, which shows this exact scenario.

这篇关于如何使用Spring 4在我的webSocket服务器中捕获订阅事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆