Sending message to client periodically via Spring Web-Socket

拟墨画扇 提交于 2019-12-20 10:43:20

问题


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?


回答1:


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");
    }

}


来源:https://stackoverflow.com/questions/42207513/sending-message-to-client-periodically-via-spring-web-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!