以下是需要解决的问题:
- 问题在于我找不到一种方法,在客户端未发送消息的情况下,服务器发送消息给客户端!
- 是否有可能列出所有已连接的WebSockets?
我的回答:
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);
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!