How to send message to client through websocket using Spring
I was able to solve my problem thanks to @Boris the Spider. The correct solution is to do something like that :
@Controller
@RequestMapping("/")
public class PhotoController {
@Autowired
private SimpMessagingTemplate template;
@MessageMapping("/form")
@SendTo("/topic/greetings")
public Greeting validate(AddPhotosForm addPhotosForm) {
FireGreeting r = new FireGreeting( this );
new Thread(r).start();
return new Greeting("Hello world !");
}
public void fireGreeting() {
System.out.println("Fire");
this.template.convertAndSend("/topic/greetings", new Greeting("Fire"));
}
}
A better way to schedule periodic tasks is, as suggested by @Boris the Spider, to use Spring scheduling mechanisms (see this guide).
For the sake of Separation of Concerns, I would also separate scheduled-related code from controller code.
In your case you could use a class like this one:
@Component
public class ScheduledTasks {
@Autowired
private SimpMessagingTemplate template;
@Scheduled(fixedRate = 2000)
public void fireGreeting() {
this.template.convertAndSend("/topic/greetings", new Greeting("Fire"));
}
}
And add the @EnableScheduling
tag to your Application class.