Spring Boot + Websocket(SockJS)

6
我正在尝试创建一个服务器,当发生更改时通知连接的客户端。为此,我使用Spring Boot作为服务器。为了发送通知,每个客户端都要与服务器建立一个套接字。我使用了这篇指南:https://spring.io/guides/gs/messaging-stomp-websocket/,它完美地运行。在这个例子中,客户端通过套接字发送消息,服务器做出响应。
以下是需要解决的问题:
  1. 问题在于我找不到一种方法,在客户端未发送消息的情况下,服务器发送消息给客户端!
  2. 是否有可能列出所有已连接的WebSockets?
谢谢。
1个回答

8

我的回答:

  1. The client does not need to send a message but they do have to connect and subscribe. I am actually doing that myself in an application where a browser connects and subscribes and then starts sending messages. On the server side you can Autowire a Service (or other Component) with a SimpMessagingTemplate object and then use the convertAndSend family of functions to send things to either a particular user or all subscribers. If you check out the portfolio project you can see how it is done with the price.stock topic. The client connects and subscribes and the server has a scheduled job to send to it. This service is using a MessageSendingOperations object but you can use SimpMessagingTemplate as mentioned above. I have this code in our application service:

    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    
    ...
    messagingTemplate.convertAndSendToUser(userId, destination, jsonMessage);
    
  2. This question has some good information on finding all users. It seems like you need to use the events defined in the Spring documentation on STOMP context events to keep track of things yourself if you want that. Generally since this is a subscription model you may not need to know who is connected. You could also build your own topic that you send out a request for all clients to respond to and look for their posts. I have not done this myself but Rossen (one of the commentors) is one of the main authors of the project so I believe him!

希望这能帮助您。请告诉我。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接