I'm trying to make a connection between client and server via Spring webSocket and I'm doing this by the help of this link. I want Controller to send a "hello" to client every 5 seconds and client append it to the greeting box every time. This is the controller class:
@EnableScheduling
@Controller
public class GreetingController {
@Scheduled(fixedRate = 5000)
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting() throws Exception {
Thread.sleep(1000); // simulated delay
System.out.println("scheduled");
return new Greeting("Hello");
}
}
and This is Connect() function in app.jsp:
function connect() {
var socket = new SockJS('/gs-guide-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.send("/app/hello", {}, JSON.stringify({'name': "connect"}));
stompClient.subscribe('/topic/greetings', function (message) {
console.log("message"+message);
console.log("message"+(JSON.parse(message.body)));
showGreeting(JSON.parse(message.body).content);
});
});
}
when the index.jsp loads and I press the connect button, only one time it appnds hello in greeting, how should I make client to show "hello" message every 5 seconds?
Please reffer to this portion of the documentation. The way you are trying to send a message is totally wrong. I would modify your above class as follows:
@EnableScheduling
@Controller
public class GreetingController {
@Autowired
private SimpMessagingTemplate template;
@Scheduled(fixedRate = 5000)
public void greeting() {
Thread.sleep(1000); // simulated delay
System.out.println("scheduled");
this.template.convertAndSend("/topic/greetings", "Hello");
}
}