春天,如何使用websockets向连接的客户端广播消息? [英] Spring, how to broadcast message to connected clients using websockets?

查看:102
本文介绍了春天,如何使用websockets向连接的客户端广播消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的应用程序中使用websockets.我遵循了本教程: http://spring.io/guides/gs/messaging-stomp-websocket/

它完美地工作.

其中一个连接的客户端按下按钮时,此方法称为:

@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting() throws Exception {
    System.out.println("Sending message...");
    Thread.sleep(1000); // simulated delay
    return new Greeting("hello!");        
}

,消息将广播到所有连接的客户端.

现在,我想修改服务器应用程序,使其能够定期(每个小时)向所有连接的客户端广播消息,而无需客户端的交互.

类似这样的东西(但这显然不能正常工作):

@Scheduled(fixedRate = 3600000)
public void sendMessage(){
   try {
   @SendTo("/topic/greetings")     
   greeting();
    } catch (Exception e) {
        e.printStackTrace(); 
    }
}

谢谢.

解决方案

@SendTo仅在SimpAnnotationMethodMessageHandler中起作用,SimpAnnotationMethodMessageHandler仅通过SubProtocolWebSocketHandler启动,以防从客户端收到WebSocketMessage./p>

要达到您的要求,您应该注入@Scheduled服务SimpMessagingTemplate brokerMessagingTemplate并直接使用它:

@Autowired
private SimpMessagingTemplate brokerMessagingTemplate;
.......
this.brokerMessagingTemplate.convertAndSend("/topic/greetings", "foo");

I am trying to use websockets in my app. I have followed this tutorial: http://spring.io/guides/gs/messaging-stomp-websocket/

It works perfectly.

When one of connected clients press button, this method is called:

@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting() throws Exception {
    System.out.println("Sending message...");
    Thread.sleep(1000); // simulated delay
    return new Greeting("hello!");        
}

and message is broadcasted to all of connected clients.

Now i want to modify my server app, that it will broadcast messages periodically (each hour) to all of my connected clients, without interaction from clients.

Something like this(but this is not working obviously):

@Scheduled(fixedRate = 3600000)
public void sendMessage(){
   try {
   @SendTo("/topic/greetings")     
   greeting();
    } catch (Exception e) {
        e.printStackTrace(); 
    }
}

Thx for advices.

解决方案

@SendTo works only in the SimpAnnotationMethodMessageHandler, which is initiated only through the SubProtocolWebSocketHandler, hance when the WebSocketMessage is received from clients.

To achieve your requirements you should inject to the your @Scheduled service SimpMessagingTemplate brokerMessagingTemplate and use it directly:

@Autowired
private SimpMessagingTemplate brokerMessagingTemplate;
.......
this.brokerMessagingTemplate.convertAndSend("/topic/greetings", "foo");

这篇关于春天,如何使用websockets向连接的客户端广播消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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