使用sockjs使用Spring 4 WebSocket无法连接套接字
尝试使用sockjs在套接字上使用带有STOMP的Spring 4 WebSocket。 我遇到了一个问题。
我的配置:
websocket.xml – spring上下文的一部分
控制器代码:
@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(""); 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。
我遵循Boris The Spider的建议,我开始使用Java配置(AppConfig和WebInit文件)而不是XML配置文件。 当我完成迁移 – 我尝试了websockets – 它是有效的! 我认为主要的问题是WebSocket的XML配置。
我认为您的问题与此问题相同,其接受的答案可以适用。
简而言之:检查您如何映射DispatcherServlet。 要使您的端点URL为http://localhost:8080/ws
,DispatcherServlet 和您的应用程序contexte root应设置为“/”。
它应该是这样的,在你的web.xml
:
WebSocketDispatcher org.springframework.web.servlet.DispatcherServlet 1 true WebSocketDispatcher /*
这或您需要在终点URL中包含上下文根和调度程序映射:
http://:///ws
我希望它可以帮到你。
问候。
Heleno的
首先,您已使用app设置目标前缀,因此您必须将“app”添加到您的请求url中。 例如,如果我想要’/ ws’,我应该用路径’/ server / app / ws’创建SockJS,你也可以用var socket = new SockJS("
你知道’server’是你在springmvc上的项目名称。
其次,必须将路径’/ app / *’添加到org.springframework.web.servlet.DispatcherServlet,以避免在web.xml中定义的拦截器截获前缀’/ app’的路径。