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

相关文章
相关标签/搜索