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

问题描述

我正在尝试通过Spring webSocket在客户端和服务器之间建立连接,而我正在此链接.我希望Controller每5秒向客户端发送一次"hello",客户端每次将其附加到问候框中.这是控制器类:

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定期向客户端发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 09:55