My requirement is to send(broadcast) a message via web-socket once some change in back end occurs.
I followed this tutorial and utilized the answer in this question to come up with a solution that send a message by periodically calling a method.
My web socket controller class - GreetingController class is like this,
@Controller
public class GreetingController {
@Autowired
private SimpMessagingTemplate template;
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
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"));
}
}
fireGreeting method is called in the thread class - FireGreeting
public class FireGreeting implements Runnable {
private GreetingController listener;
public FireGreeting( GreetingController listener) {
this.listener = listener;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep( 2000 );
listener.fireGreeting();
} catch ( InterruptedException e ) {
e.printStackTrace();
}
}
}
}
When i run this project i can send a message initially and then the thread starts periodically calling the fireGreeting() method.
What i wan't is to without calling the greeting(HelloMessage message) method, call the fireGreeting() method whenever my back-end operation is run.
I tried calling the method separately but it gives a null pointer exception because at that point SimpMessagingTemplate template;
is not initialized.
My questions are as follows, 1.When does the template object get initialized? (So i can do the same thing and use it to call convertAndSend() method)
Is it impossible to call the convertAndSend method like the way im trying to?
Is there any other way i can achieve this requirement in spring and websocket?
I also tried this code in the documentation, but i don't have a clear understanding on how it works. It seems like, i can send a POST call and invoke the greet() method so it sends a message to server. But what i want is to invoke the method solely from the server side.
Any advice regarding this would be a great help. :)