java - Spring应用服务器通过websocket向客户端传输数据

标签 java spring websocket server client

问题:是否可以在 Spring 中使用 websocket 将数据从服务器发送到客户端,而无需在支持服务器的 java 应用程序中创建另一个客户端?

互联网上几乎所有关于 spring 中 websocket 的文章都展示了如何在 Controller 中定义处理请求的方法。当他们用两个注释 @MessageMapping("/news") 、 @SendTo("/topic/news") 定义一个函数时,所有的魔法似乎都发生了。据我所知,仅通过此方法,您只能捕获请求并将其进一步发送(SendTo)。我想知道是否可以在客户端不首先请求某些内容的情况下将数据从服务器发送到客户端。以及该代码的外观。

最佳答案

您可以使用 SimpMessagingTemplate 。

我认为你应该在某个地方上这门课

 @Configuration
 @EnableWebSocketMessageBroker
 public class "yournameclass" extends AbstractWebSocketMessageBrokerConfigurer

然后里面这个方法

@Override
public void configureMessageBroker(MessageBrokerRegistry configuration) {
    configuration.enableSimpleBroker("/test");
    configuration.setApplicationDestinationPrefixes("/someprefix"); 
}

然后你可以从代码中的某个方法调用它

@Autowired
private SimpMessagingTemplate template;


public void "mymethodsender" ()
{  this.template.convertAndSend("/test/somepathwhereyouregisteredyourclienttoreceivemessages", "messageobject");
}

关于java - Spring应用服务器通过websocket向客户端传输数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57514486/

相关文章:

javascript - Node.js 和 web-socket-js 简单客户端服务器未打开

android - Websocket 在非浏览器设备上的开销

java - 我可以使用方法在 Java 中进行类转换吗?

java - 数组列表中的数组列表

java - 错误:Log already in use?

spring - 使用 OAuth2 : Error creating bean with name 'scopedTarget.oauth2ClientContext' : Scope 'session' is not active 保护 REST API

java - 在 Spring security 中并发 session 的情况下使第一个登录 session 无效

spring - @Configuration 和 @Component 之间的行为差​​异

java - JSONObject 没有按应有的方式进行编码?

internet-explorer - IE是否有任何websocket插件?