我想在 Spring Boot 应用程序中使用 java websocket API。 我按照此处所述创建了以下类: https://www.baeldung.com/java-websockets
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
@ServerEndpoint(value = "/test")
public class FrontendEndpoint {
@OnOpen
public void onOpen(Session session) throws IOException {
session.getBasicRemote().sendText("Test");
}
@OnMessage
public void onMessage(Session session, String message) throws IOException {
}
@OnClose
public void onClose(Session session) throws IOException {
}
@OnError
public void onError(Session session, Throwable throwable) {
}
}
我尝试连接到该 websocket,但没有任何反应。我在互联网上看到了很多文章,但没有任何帮助我。我不知道如何让它发挥作用。
当我尝试连接到 websocket 时,什么也没发生。
Spring Boot版本:2.0.3
Websocket-API 版本:1.1
我也没有看到 websocket 的开放端口。
谢谢
BR
最佳答案
有点晚了,但万一有人会来这里寻求解决方案。
Spring 文档中没有介绍如何在 Spring 中使用 Java WebSocket API (JSR-356),而且我也没有找到任何描述如何实现它的教程,尽管我花了几个小时在谷歌上搜索它。
为了在 Spring 中使用 Java WebSocket API,您应该使用类 org.springframework.web.socket.server.standard.SpringConfigurator: https://docs.spring.io/spring/docs/current/javadoc-api/index.html?org/springframework/web/socket/server/standard/SpringConfigurator.html 来自
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>...</version>
</dependency>
只需将其添加到您的
@ServerEndpoint(... configurator = SpringConfigurator.class)
就这样完成了。带注释的类成为常见的 Spring 管理组件,对于 @Autowired 注入(inject)等合法。
希望它能帮助别人:)
更新。
应该提到的是,通过 SpringConfigurator 进行 JSR 356 WebSocket 初始化仅在 .war 项目中受支持,这些项目将像平常的工件一样部署在 servlet 容器中。
当项目打包在可执行的 Spring Boot .jar 或 Spring Boot 可执行的 .war 中以及通过 java -jar {app} 部署为独立模式时,它将无法按预期工作
我没有找到一种方法在可执行存档的 Spring Boot 环境中使用 @Autowired Spring 组件初始化 JSR 356 WebSocket。
可以通过 ServerEndpointExporter.setAnnotatedEndpointClasses(...) 部署 JSR 356 WebSocket ,但提供的每个类必须有一个无参数构造函数,否则将引发异常。在这种情况下,@Autowired 字段将不会被 Spring 处理。
关于java - 在 Spring Boot 应用程序中使用 Java Websocket API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52185059/