在本文中,我们将为您详细介绍WebSocketsJSR356Spring集成@ServerEndpoint的相关知识,并且为您解答关于springwebsocket集群的疑问,此外,我们还会提供一些关
在本文中,我们将为您详细介绍WebSockets JSR 356 Spring集成@ServerEndpoint的相关知识,并且为您解答关于spring websocket集群的疑问,此外,我们还会提供一些关于Error creating bean with name ''webSocketServer''(springboot 整合 webstock)、io.undertow.websockets.jsr.ServerWebSocketContainer cannot be cast to org.apache.tomcat.websocket...、java – 使用sockjs stomp over socket无法连接Spring 4 WebSocket、javax.websocket.server.ServerEndpointConfig.Configurator的实例源码的有用信息。
本文目录一览:- WebSockets JSR 356 Spring集成@ServerEndpoint(spring websocket集群)
- Error creating bean with name ''webSocketServer''(springboot 整合 webstock)
- io.undertow.websockets.jsr.ServerWebSocketContainer cannot be cast to org.apache.tomcat.websocket...
- java – 使用sockjs stomp over socket无法连接Spring 4 WebSocket
- javax.websocket.server.ServerEndpointConfig.Configurator的实例源码
WebSockets JSR 356 Spring集成@ServerEndpoint(spring websocket集群)
问题:@ServerEndpoint类中的@Autowired bean为空
我如何确保下面的WebSocketController类将被注入bean,那怎么使它由Spring管理?我可以连接到websocket,这样它就可以工作,但是gameService在WebSocketController类实例中始终为null,因此我认为它是由tomcat创建的,而不是Spring创建的。
我正在使用Spring Boot。我只需要弄清楚如何将bean注入此websocket控制器类。
WebSocketController类
@Component@ServerEndpoint("/sock")public class WebSocketController { @Autowired private GameService gameService; private static Set<Session> clients = Collections.synchronizedSet(new HashSet<Session>()); @OnMessage public void handleMessage(Session session, String message) throws IOException { session.getBasicRemote().sendText( "Reversed: " + new StringBuilder(message).reverse()); } @OnOpen public void onOpen(Session session) { clients.add(session); System.out.println("New client @"+session.getId()); if (gameService == null) System.out.println("game service null"); } @OnClose public void onClose(Session session) { clients.remove(session); System.out.println("Client disconnected @" + session.getId()); }}
GameService接口和实现
public interface GameService { List<Character> getCharacters();}@Servicepublic class GameServiceMockImpl implements GameService { @Override public List<Character> getCharacters() { List<Character> list = new ArrayList<>(); list.add(new Character("aaa","1.png",100)); list.add(new Character("aaa","2.jpg",100)); list.add(new Character("aaa","3.jpg",100)); return list; }}
应用类别
@SpringBootApplicationpublic class App { public static void main(String args[]){ SpringApplication.run(App.class,args); } @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); }}
编辑:
使用Spring 4 WebSockets根本不起作用,我什至无法通过浏览器进行连接。
@Configuration@EnableWebSocketpublic class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myHandler(), "/myHandler"); } @Bean public WebSocketHandler myHandler() { return new MyHandler(); }}public class MyHandler extends TextWebSocketHandler { @Override public void handleTextMessage(WebSocketSession session, TextMessage message) { System.out.println(message.getPayload()); }}
答案1
小编典典您正在尝试集成Spring和Java WebSocket API。由注释的类@Component
已注册到spring
bean,其实例由spring管理,但是如果由注释的类@ServerEndpoint
已注册到服务器端WebSocket端点,并且每次相应端点的WebSocket连接到服务器,则其实例为由JWA实施创建和管理。我们不能同时使用两个注释。
您可以使用CDI注入(您的服务器也应支持)
@ServerEndpoint("/sock")public class WebSocketController { @Inject private GameService gameService;
或者看看这个文档,Spring 4支持WebSocket
Error creating bean with name ''webSocketServer''(springboot 整合 webstock)
今天踩了一个坑记录下,springboot 项目,整合 webstock, 总是报以下错误
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ''webSocketServer'': Lookup method resolution failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class
...
Caused by: java.lang.IllegalStateException: Failed to introspect Class [com.safesys.monitoring.util.WebSocketServer] from ClassLoader [org.springframework.boot.devtools.restart.classloader.RestartClassLoader@2f6f3352]
...
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:248)
...
Caused by: java.lang.ClassNotFoundException: javax.websocket.Session
...
Disconnected from the target VM, address: ''127.0.0.1:50767'', transport: ''socket''
刚刚开始,各种找错,发现只要添加 ServerEndpointExporter 就报错了
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
也找过很多帖子,让你注释启动test类的@RunWith(SpringRunner.class) 或者修改@SpringBootTest为测试环境之类的
反正各种找,准备放弃的时候,我尝试看看 tomcate 自身问题,因为要打 war,之前 pom 做过修改
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<!--声明spring boot内嵌tomcat的作用范围 在运行时不起作用-->
<scope>provided</scope>
</dependency>
看了注释,我注释了<scope>provided</scope> ,然后刷新包,发现真可以启动了,暂时先记录下,这个还是容器依赖的问题,要让springboot内置tomcate和web生效才行,没时间,就到这把,记录下
io.undertow.websockets.jsr.ServerWebSocketContainer cannot be cast to org.apache.tomcat.websocket...
Caused by: java.lang.ClassCastException:
io.undertow.websockets.jsr.ServerWebSocketContainer cannot be cast to org.apache.tomcat.websocket.server.WsServerContainer
at org.springframework.web.socket.server.standard.TomcatRequestUpgradeStrategy.getContainer(TomcatRequestUpgradeStrategy.java:84)
at org.springframework.web.socket.server.standard.TomcatRequestUpgradeStrategy.getContainer(TomcatRequestUpgradeStrategy.java:47)
at org.springframework.web.socket.server.standard.AbstractStandardUpgradeStrategy.getSupportedExtensions(AbstractStandardUpgradeStrategy.java:88)
at org.springframework.web.socket.server.support.AbstractHandshakeHandler.doHandshake(AbstractHandshakeHandler.java:272)
at org.springframework.web.socket.server.support.WebSocketHttpRequestHandler.handleRequest(WebSocketHttpRequestHandler.java:166)
... 56 common frames omitted
问题产生原因是:pom 引入的依赖包 undertow 与 websocket 依赖包中的 tomcat 冲突了导致,如下:
<!--undertow-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<!--websocket依赖包中本身也依赖tomcat-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
解决方案:
<!--websocket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
java – 使用sockjs stomp over socket无法连接Spring 4 WebSocket
我遇到了一个问题.
我的配置:
websocket.xml – spring上下文的一部分
<websocket:message-broker application-destination-prefix="/app"> <websocket:stomp-endpoint path="/ws"> <websocket:sockjs/> </websocket:stomp-endpoint> <websocket:simple-broker prefix="/topic"/> </websocket:message-broker>
控制器代码:
@MessageMapping("/ws") @SendTo("/topic/ws") public AjaxResponse hello() throws Exception { AjaxResponse ajaxResponse = new AjaxResponse(); ajaxResponse.setSuccess(true); ajaxResponse.addSuccessMessage("WEB SOCKET!!! HELL YEAH!"); return ajaxResponse; }
客户端:
var socket = new SockJS("<c:url value='/ws'/>"); var stompClient = Stomp.over(socket); stompClient.connect({},function(frame) { alert('Connected: ' + frame); stompClient.send("/app/ws",{},{}); stompClient.subscribe('/topic/ws',function(response){ alert(response.success); }); });
输出:
opening Web Socket... stomp.js:130 GET http://localhost:8080/ws/info 404 (Not Found) sockjs-0.3.js:807 Whoops! Lost connection to undefined stomp.js:130
我做错了什么?
我在谷歌找到了一些例子(TickerStocks或类似的东西,问候应用程序(Spring的例子)),所有这些都给了我同样的错误.我尝试使用WebSocket与握手(没有sockjs) – 相同的结果).
补充资料:
方法public AjaxResponse hello();放在根上下文“/”的IndexController中.所以我可以提供完整的路径:http:// localhost:8080 / ws.
要部署经过测试的tomcat7和tomcat8.
解决方法
javax.websocket.server.ServerEndpointConfig.Configurator的实例源码
/** * * @param context the context to add the web socket endpoints to * @param rtEventResource The instance of the websocket endpoint to return * @throws DeploymentException */ private static void setWebSocketEndpoints(ServletContextHandler context,EventsResource rtEventResource) throws DeploymentException,servletexception { ServerContainer wsContainer = WebSocketServerContainerInitializer.configureContext(context); ServerEndpointConfig serverConfig = ServerEndpointConfig.Builder .create(EventsResource.class,EventsResource.RT_EVENT_ENDPOINT) .configurator(new Configurator() { @Override public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException { return endpointClass.cast(rtEventResource); } }).build(); wsContainer.addEndpoint(serverConfig); }
@Override protected void startServer(int port,final Action<ServerWebSocket> websocketAction) throws Exception { server = new Server(); ServerConnector connector = new ServerConnector(server); connector.setPort(port); server.addConnector(connector); ServletContextHandler handler = new ServletContextHandler(); server.setHandler(handler); ServerContainer container = WebSocketServerContainerInitializer.configureContext(handler); ServerEndpointConfig config = ServerEndpointConfig.Builder.create(AsityServerEndpoint.class,TEST_URI) .configurator(new Configurator() { @Override public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException { return endpointClass.cast(new AsityServerEndpoint().onwebsocket(websocketAction)); } }) .build(); container.addEndpoint(config); server.start(); }
@Override protected void startServer() throws Exception { server = new Server(); ServerConnector connector = new ServerConnector(server); connector.setPort(port); server.addConnector(connector); ServletContextHandler handler = new ServletContextHandler(); server.setHandler(handler); ServerContainer container = WebSocketServerContainerInitializer.configureContext(handler); ServerEndpointConfig config = ServerEndpointConfig.Builder.create(VibeServerEndpoint.class,"/test") .configurator(new Configurator() { @Override public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException { return endpointClass.cast(new VibeServerEndpoint().onwebsocket(performer.serverAction())); } }) .build(); container.addEndpoint(config); server.start(); }
public static void init(final ServletContextHandler context,final MinijaxApplication application) throws servletexception,DeploymentException { final ServerContainer container = WebSocketServerContainerInitializer.configureContext(context); final Configurator configurator = new MinijaxWebSocketConfigurator(application); for (final Class<?> c : application.getWebSockets()) { final ServerEndpointConfig config = ServerEndpointConfig.Builder .create(c,c.getAnnotation(ServerEndpoint.class).value()) .configurator(configurator) .build(); container.addEndpoint(config); } }
今天关于WebSockets JSR 356 Spring集成@ServerEndpoint和spring websocket集群的分享就到这里,希望大家有所收获,若想了解更多关于Error creating bean with name ''webSocketServer''(springboot 整合 webstock)、io.undertow.websockets.jsr.ServerWebSocketContainer cannot be cast to org.apache.tomcat.websocket...、java – 使用sockjs stomp over socket无法连接Spring 4 WebSocket、javax.websocket.server.ServerEndpointConfig.Configurator的实例源码等相关知识,可以在本站进行查询。
本文标签: