Good starting points to build a Spring Boot application with Websocket support are
To determine connected users you can use SimpUserRegistry
bean and to send messages to them you can use SimpMessagingTemplate
, for example:
@RestController
public class ApiController {
private final SimpMessagingTemplate template;
private final SimpUserRegistry userRegistry;
public ApiController(SimpMessagingTemplate template, SimpUserRegistry userRegistry) {
this.template = template;
this.userRegistry = userRegistry;
}
@PostMapping("/api/users/{username}/send")
public ResponseEntity<?> sendMessage(@RequestBody Message message, @PathVariable String username) {
Set<SimpUser> users = userRegistry.getUsers();
if (users.stream().anyMatch(simpUser -> simpUser.getName().equals(username))) {
template.convertAndSendToUser(username, "/messages", message);
return ResponseEntity.noContent().build();
} else {
return ResponseEntity.notFound().build();
}
}
}
You can check my minimal example of working Websockets demo application.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…