我正在尝试在Spring 4.0 Web应用程序中实现以下Websockets示例:
http://spring.io/guides/gs/messaging-stomp-websocket/
我有以下配置文件:
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/");
config.setApplicationDestinationPrefixes("/");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/socket/init").withSockJS();
}
}
以下是我在SockJS和Stomp.js客户端上使用的JavaScript:
var stompClient = null;
var socket = new SockJS('/HR/socket/init');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
console.log('Connected: ' + frame);
stompClient.send("/HR/get/staff", {}, JSON.stringify({ 'country': 'United Kingdom', 'city': 'London' }));
stompClient.subscribe('/HR/new/staff', function(message){
console.log(message);
});
});
创建套接字连接时,我收到一个类强制转换异常,如下所示:
java.lang.ClassCastException: org.apache.tomcat.websocket.server.WsServerContainer cannot be cast to javax.websocket.server.ServerContainer
我在另一个StackOverflow问题上看到了同样的问题,遗憾的是该解决方案没有解决我的问题,因为我没有在build.gradle文件中包含javax.websocket-api。我试过把它包括在内并排除它,我得到了同样的错误。我正在使用Tomcat 8.0.14。
注意:完全相同的代码库已在Tomcat 7上使用Java 7进行测试并且可以正常运行。当我转换到Java 8并在Tomcat 8上运行时,我得到了上面的例外。