通过Spring Web-Socket定期向客户端发送消息 [英] Sending message to client periodically via Spring Web-Socket

查看:357
本文介绍了通过Spring Web-Socket定期向客户端发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Spring webSocket在客户端和服务器之间建立连接,而我正在

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

}

这是app.jsp中的Connect()函数:

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

当index.jsp加载并且我按下connect按钮时,只有一次它在问候语中打招呼时,我应该如何使客户端每5秒显示一次"hello"消息?

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

}

这篇关于通过Spring Web-Socket定期向客户端发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆