java 通过 Spring Web-Socket 定期向客户端发送消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42207513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:27:24  来源:igfitidea点击:

Sending message to client periodically via Spring Web-Socket

javaspringspring-bootwebsocketsockjs

提问by ShakibaZar

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:

我正在尝试通过 Spring webSocket 在客户端和服务器之间建立连接,并且我是在此链接的帮助下完成的。我希望控制器每 5 秒向客户端发送一个“你好”,客户端每次都将它附加到问候框中。这是控制器类:

@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:

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

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?

当 index.jsp 加载并且我按下连接按钮时,它只有一次在问候语中附加 hello,我应该如何让客户端每 5 秒显示一次“hello”消息?

回答by Andrei Balici

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

}