前端使用sockjs,後臺使用spring的websocket框架html
結果在一個網絡較慢的地方,發現tomcat報錯信息:前端
Oct 28, 2015 10:10:43 AM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet [mvc-dispatcher] in context with path [/rscc] threw exception [Request processing failed; nested exception is org.springframework.web.socket.sockjs.SockJsException: Uncaught failure in SockJS request, uri=http://xxx/user/854/qckzogtf/xhr_streaming; nested exception is org.springframework.web.socket.sockjs.SockJsException: Uncaught failure for request http://xxx/user/854/qckzogtf/xhr_streaming; nested exception is java.lang.IllegalArgumentException: Async support must be enabled on a servlet and for all filters involved in async request processing. This is done in Java code using the Servlet API or by adding "<async-supported>true</async-supported>" to servlet and filter declarations in web.xml. Also you must use a Servlet 3.0+ container] with root cause java.lang.IllegalArgumentException: Async support must be enabled on a servlet and for all filters involved in async request processing. This is done in Java code using the Servlet API or by adding "<async-supported>true</async-supported>" to servlet and filter declarations in web.xml. Also you must use a Servlet 3.0+ container at org.springframework.util.Assert.isTrue(Assert.java:65) at org.springframework.http.server.ServletServerHttpAsyncRequestControl.<init>(ServletServerHttpAsyncRequestControl.java:59) at org.springframework.http.server.ServletServerHttpRequest.getAsyncRequestControl(ServletServerHttpRequest.java:202) at org.springframework.web.socket.sockjs.transport.session.AbstractHttpSockJsSession.initRequest(AbstractHttpSockJsSession.java:238) at org.springframework.web.socket.sockjs.transport.session.AbstractHttpSockJsSession.handleInitialRequest(AbstractHttpSockJsSession.java:203) at org.springframework.web.socket.sockjs.transport.session.StreamingSockJsSession.handleInitialRequest(StreamingSockJsSession.java:54) at org.springframework.web.socket.sockjs.transport.handler.AbstractHttpSendingTransportHandler.handleRequestInternal(AbstractHttpSendingTransportHandler.java:66) at org.springframework.web.socket.sockjs.transport.handler.AbstractHttpSendingTransportHandler.handleRequest(AbstractHttpSendingTransportHandler.java:58) at org.springframework.web.socket.sockjs.transport.TransportHandlingSockJsService.handleTransportRequest(TransportHandlingSockJsService.java:254) at org.springframework.web.socket.sockjs.support.AbstractSockJsService.handleRequest(AbstractSockJsService.java:317) at org.springframework.web.socket.sockjs.support.SockJsHttpRequestHandler.handleRequest(SockJsHttpRequestHandler.java:88) at org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter.handle(HttpRequestHandlerAdapter.java:51) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863) at javax.servlet.http.HttpServlet.service(HttpServlet.java:646) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745)
根據報錯信息來看,應該是缺乏了<async-supported>true</async-supported>這個配置,這個是3.0開始支持的,async的請求須要開啓async-supported。java
可是該項目在咱們本地歷來沒有出現過這個問題,狀況說明及解決分析過程以下:web
1、前端鏈接狀況:ws = new SockJS( 'url', undefined, {});spring
不加參數,sockjs默認會選擇最優方式來鏈接,狀況以下:apache
關於協議選擇:在第一種鏈接方式超時時,sockjs會選擇次優方式進行鏈接:json
var _all_protocols = ['websocket', 'xdr-streaming', 'xhr-streaming', 'iframe-eventsource', 'iframe-htmlfile', 'xdr-polling', 'xhr-polling', 'iframe-xhr-polling', 'jsonp-polling']; 全部協議(鏈接方式)
檢測全部可用協議並按優先級排序tomcat
utils.probeProtocols = function() { var probed = {}; for(var i=0; i<_all_protocols.length; i++) { var protocol = _all_protocols[i]; // User can have a typo in protocol name. probed[protocol] = SockJS[protocol] && SockJS[protocol].enabled(); } return probed; }; utils.detectProtocols = function(probed, protocols_whitelist, info) { var pe = {}, protocols = []; if (!protocols_whitelist) protocols_whitelist = _all_protocols; for(var i=0; i<protocols_whitelist.length; i++) { var protocol = protocols_whitelist[i]; pe[protocol] = probed[protocol]; } var maybe_push = function(protos) { var proto = protos.shift(); if (pe[proto]) { protocols.push(proto); } else { if (protos.length > 0) { maybe_push(protos); } } } // 1. Websocket if (info.websocket !== false) { maybe_push(['websocket']); } // 2. Streaming if (pe['xhr-streaming'] && !info.null_origin) { protocols.push('xhr-streaming'); } else { if (pe['xdr-streaming'] && !info.cookie_needed && !info.null_origin) { protocols.push('xdr-streaming'); } else { maybe_push(['iframe-eventsource', 'iframe-htmlfile']); } } // 3. Polling if (pe['xhr-polling'] && !info.null_origin) { protocols.push('xhr-polling'); } else { if (pe['xdr-polling'] && !info.cookie_needed && !info.null_origin) { protocols.push('xdr-polling'); } else { maybe_push(['iframe-xhr-polling', 'jsonp-polling']); } } return protocols; }
鏈接時若超時切換協議的代碼websocket
while(1) { var protocol = that.protocol = that._protocols.shift(); if (!protocol) { return false; } // Some protocols require access to `body`, what if were in // the `head`? if (SockJS[protocol] && SockJS[protocol].need_body === true && (!_document.body || (typeof _document.readyState !== 'undefined' && _document.readyState !== 'complete'))) { that._protocols.unshift(protocol); that.protocol = 'waiting-for-load'; utils.attachEvent('load', function(){ that._try_next_protocol(); }); return true; } //下面的to = 就是計算鏈接超時時間的,調用delay,在鏈接超時時關閉這個協議的鏈接。 if (!SockJS[protocol] || !SockJS[protocol].enabled(that._options)) { that._debug('Skipping transport:', protocol); } else { var roundTrips = SockJS[protocol].roundTrips || 1; var to = ((that._options.rto || 0) * roundTrips) || 5000; that._transport_tref = utils.delay(to, function() { if (that.readyState === SockJS.CONNECTING) { // I can't understand how it is possible to run // this timer, when the state is CLOSED, but // apparently in IE everythin is possible. that._didClose(2007, "Transport timeouted"); } }); var connid = utils.random_string(8); var trans_url = that._base_url + '/' + that._server + '/' + connid; that._debug('Opening transport:', protocol, ' url:'+trans_url, ' RTO:'+that._options.rto); that._transport = new SockJS[protocol](that, trans_url, that._base_url); return true; } }
觀察上面報錯信息中的uri:uri=http://xxx/user/854/qckzogtf/xhr_streaming; 由於正常狀況下鏈接爲websocket鏈接,這個uri應該爲ws=http://xxx/user/854/qckzogtf/websocket,因而可知,這裏應該是切換爲xhr_streaming協議了cookie
前面也說過,他們網絡環境較慢,因此纔想,應該是鏈接超時致使的,有上面可知,to爲超時時間,計算公式爲
var to = ((that._options.rto || 0) * roundTrips) || 5000;
關鍵在於that._options.rto,這個是new的時候的設置項,因此能夠設置rto超時長一點。
結果發現設置中只有
that._options = {devel: false, debug: false, protocols_whitelist: [],info: undefined, rtt: undefined};
這幾項,並無rto,因而繼續看
var SockJS = function(url, dep_protocols_whitelist, options) { if (this === _window) { // makes `new` optional return new SockJS(url, dep_protocols_whitelist, options); } var that = this, protocols_whitelist; that._options = {devel: false, debug: false, protocols_whitelist: [], info: undefined, rtt: undefined}; if (options) { utils.objectExtend(that._options, options); } that._base_url = utils.amendUrl(url); that._server = that._options.server || utils.random_number_string(1000); if (that._options.protocols_whitelist && that._options.protocols_whitelist.length) { protocols_whitelist = that._options.protocols_whitelist; } else { // Deprecated API if (typeof dep_protocols_whitelist === 'string' && dep_protocols_whitelist.length > 0) { protocols_whitelist = [dep_protocols_whitelist]; } else if (utils.isArray(dep_protocols_whitelist)) { protocols_whitelist = dep_protocols_whitelist } else { protocols_whitelist = null; } if (protocols_whitelist) { that._debug('Deprecated API: Use "protocols_whitelist" option ' + 'instead of supplying protocol list as a second ' + 'parameter to SockJS constructor.'); } } that._protocols = []; that.protocol = null; that.readyState = SockJS.CONNECTING; that._ir = createInfoReceiver(that._base_url); that._ir.onfinish = function(info, rtt) { that._ir = null; if (info) { if (that._options.info) { // Override if user supplies the option info = utils.objectExtend(info, that._options.info); } if (that._options.rtt) { rtt = that._options.rtt; } that._applyInfo(info, rtt, protocols_whitelist); that._didClose(); } else { that._didClose(1002, 'Can\'t connect to server', true); } }; };
utils.objectExtend(that._options, options);這一句比較可疑是轉移屬性的,
that._applyInfo(info, rtt, protocols_whitelist);比較可疑,看一下
SockJS.prototype._applyInfo = function(info, rtt, protocols_whitelist) { var that = this; that._options.info = info; that._options.rtt = rtt; that._options.rto = utils.countRTO(rtt); that._options.info.null_origin = !_document.domain; var probed = utils.probeProtocols(); that._protocols = utils.detectProtocols(probed, protocols_whitelist, info); };
rto設置找到了!that._options.rto = utils.countRTO(rtt);
utils.countRTO = function (rtt) { var rto; if (rtt > 100) { rto = 3 * rtt; // rto > 300msec } else { rto = rtt + 200; // 200msec < rto <= 300msec } return rto; }
好了,只用設置rtt既能夠設置rto了。。。就這樣,鏈接超時的問題算是解決了。
2、可是還沒完,就算websocket鏈接超時致使協議切換爲xhr_streaming,也不會致使後臺報錯的狀況出現,下面解決這個問題:
報錯處的代碼:在AbstractHttpSockJsSession類中:
private void initRequest(ServerHttpRequest request, ServerHttpResponse response, SockJsFrameFormat frameFormat) { Assert.notNull(request, "Request must not be null"); Assert.notNull(response, "Response must not be null"); Assert.notNull(frameFormat, "SockJsFrameFormat must not be null"); this.response = response; this.frameFormat = frameFormat; this.asyncRequestControl = request.getAsyncRequestControl(response); }
最後一句報錯咯,看代碼:
public ServerHttpAsyncRequestControl getAsyncRequestControl(ServerHttpResponse response) { if (this.asyncRequestControl == null) { Assert.isInstanceOf(ServletServerHttpResponse.class, response); ServletServerHttpResponse servletServerResponse = (ServletServerHttpResponse) response; this.asyncRequestControl = new ServletServerHttpAsyncRequestControl(this, servletServerResponse);//這一句報錯了 } return this.asyncRequestControl; }
new ServletServerHttpAsyncRequestControl時報錯
public ServletServerHttpAsyncRequestControl(ServletServerHttpRequest request, ServletServerHttpResponse response) { Assert.notNull(request, "request is required"); Assert.notNull(response, "response is required"); Assert.isTrue(request.getServletRequest().isAsyncSupported(), "Async support must be enabled on a servlet and for all filters involved " + "in async request processing. This is done in Java code using the Servlet API " + "or by adding \"<async-supported>true</async-supported>\" to servlet and " + "filter declarations in web.xml. Also you must use a Servlet 3.0+ container"); this.request = request; this.response = response; }
最長那一句斷言報的錯,說的是web.xml的servlet和filter中要加入<async-supported>true</async-supported>
看下web.xml中,filter中確實沒有這一句,之因此必定要在filter中加入這一句,是由於websocket的切換協議請求,是經過filter攔截的,若是不在filter中配置async,則切換協議的請求將不是async的,因此上面就報錯了。
filter中加上以後,就行了。
若爲了讓controller也支持async則須要在dispatcher中這樣配置
<mvc:annotation-driven>
<!-- 可不設置,使用默認的超時時間 -->
<mvc:async-support default-timeout="3000"/>
</mvc:annotation-driven>
再返回上面initRequest方法,只有該類AbstractHttpSockJsSession的public void handleInitialRequest(ServerHttpRequest request, ServerHttpResponse response,SockJsFrameFormat frameFormat)方法與
public void handleSuccessiveRequest(ServerHttpRequest request,ServerHttpResponse response, SockJsFrameFormat frameFormat)中有調用,而調用這兩個方法的只有AbstractHttpSockJsSession的實現類:StreamingSockJsSession纔有,就是spring-websocket爲sockjs支持的xhr-streaming方式的實現類,而平時使用websocket的則是另一個實現類:
這就致使了以前一直沒有報錯,上了一個網絡較差的地方就報錯了,緣由分析完畢。
上面用的sockjs 0.3.4,最新的是1.0.3有所改變,可是大體相同
補充:相同個毛線,1.0.3的rtt再也不是經過參數傳進去的,而是計算出來的
function InfoAjax(url, AjaxObject) { EventEmitter.call(this); var self = this; var t0 = +new Date(); this.xo = new AjaxObject('GET', url); this.xo.once('finish', function(status, text) { var info, rtt; if (status === 200) { rtt = (+new Date()) - t0; if (text) { try { info = JSON3.parse(text); } catch (e) { debug('bad json', text); } } if (!objectUtils.isObject(info)) { info = {}; } } self.emit('finish', info, rtt); self.removeAllListeners(); }); }
也就是說,超時時間控制不了的...什麼鬼
this._transportsWhitelist = options.transports;這個是設置白名單,優先使用這些方式。