简体   繁体   中英

Spring Boot + Websocket (SockJS)

I'm trying to make a server that notifies connected clients when changes occur. For that, I'm using Spring Boot for the server. In order to deliver notifications, each client establish a socket with the server. I used this guide : https://spring.io/guides/gs/messaging-stomp-websocket/ and it works perfectly. In this example, the client send a message over the socket and the server responds.

  1. The problem is that I can't find out a way where the server sends a message to client without having the client to send a message first!
  2. Is it possible to list all connected websockets ?

Thank you,

My answers:

  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!

Hopefully this helps. Let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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