我正在尝试通过Spring webSocket在客户端和服务器之间建立连接,并且通过此链接来实现此目的。我希望Controller每5秒向客户端发送一次“ hello”,客户端每次将其附加到问候框中。这是控制器类:
@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()函数:
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加载并且我按下连接按钮时,只有一次它向问候打招呼,我应该如何使客户端每5秒显示一次“ hello”消息?
请参考文档的这一部分。您尝试发送消息的方式是完全错误的。我将修改您的上述课程,如下所示:
@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"); } }