spring4+websocket(兼容低版本ie)

轉載請註明: TheViper http://www.cnblogs.com/TheViper html

效果html5

 

不支持websocket的瀏覽器,用flash模擬websocket.固然,也能夠用flash socket直接與服務端socket鏈接。git

經過用flash模擬websocket,至少讓全部瀏覽器在後端有一個統一的解決方案,不用單獨爲不支持websocket的瀏覽器寫長鏈接,socket鏈接,解析等其餘的代碼。github

事實上,websocket協議比較簡單,用actionscript模擬也比較簡單,這個在本屌的另一篇文章讓ie6 7 8 9支持html5 websocket簡單說了下。web

另外,spring爲sockjs 提供api,只需簡單配置下,就能夠兼容低版本瀏覽器,原理是用js模擬websocket object。具體的本屌尚未去看。spring

幾點說明:後端

1.使用spring對websocket的封裝既能夠單獨使用,也能夠和spring mvc一塊兒使用。須要注意的是,單獨使用時,仍然要在web.xml中配置spring的dispatcher,仍然要打開server.api

    <servlet>
        <servlet-name>websocket</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>  
                /WEB-INF/applicationContext.xml 
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>websocket</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

2.單獨使用時,若refer跨域,須要在spring中設置白名單跨域

    <websocket:handlers allowed-origins="*">
             ........
    </websocket:handlers>

3.因爲用到了flash,因此須要開啓843端口,並在flash請求policy文件時,返回policy文件。例子中用的是netty4.瀏覽器

4.須要對握手進行攔截,監聽。由於在後面的websocket處理類中,沒法從WebSocketSession得到Httpsession.另外,這裏得到session要保存到arrtibutes中,在websocket處理類中,WebSocketSession調用getAttributes()方法就能夠得到arrtibutes了。

public class ChatIntercepter extends HttpSessionHandshakeInterceptor{
    
    @Override
    public boolean beforeHandshake(ServerHttpRequest request,
            ServerHttpResponse response, WebSocketHandler wsHandler,
            Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpSession session = servletRequest.getServletRequest().getSession(false);
            if (session != null) {
                String userName = (String) session.getAttribute("user");
                attributes.put("user",userName);
            }
        }
        System.out.println("Before Handshake"+request.getHeaders());
//        return super.beforeHandshake(request, response, wsHandler, attributes);
        return true;
    }
     ..............

}

5.在web-socket-js 中,flash模擬的websocket頭信息中會包含cookie,不過是人工經過腳本添加的。因此要避免須要的cookie,如session cookie是httponly.這就須要設置容器。

若是當前是在eclipse中開發

能夠看到在context標籤上添加useHttpOnly='false'就能夠了,而context標籤是eclipse部署時自動添加的。

若是已經打包了,就到tomcat目錄/conf/server.xml,在最後的</Host>前面添加

<Context docBase="websocket" path="/websocket" reloadable="true" useHttpOnly='false'/>

 本文例子下載,flash源碼在讓ie6 7 8 9支持html5 websocket文中。swf地址不要跨域,在這裏就不能爲http://localhost/websocket/...swf.若是有其餘問題,參見web-socket.js.

最後注意,這種方案看起來很美好,仍然可能出問題,參見本屌的文章http://www.cnblogs.com/TheViper/p/4152325.html

相關文章
相關標籤/搜索