Spring-websocket不在Springmvc的环境下使用

来源:互联网 发布:iphone摄影曝光软件 编辑:程序博客网 时间:2024/05/21 14:04

Spring4提供了对websocket的支持,但是网上的demo都是在Spring mvc的环境下使用的。

其实Spring-websocket是不依赖springmvc的。

其中的关键在于将websocket的地址映射到url上,供前端触发。

并且,websocket第一次是通过http来得到调用的。

也就是说,客户端第一次请求是http.而不是websocket。

这里笔者是有证据的。

打开浏览器控制台。我们可以看到。


我们可以看到http响应码为101,并且http请求头有一个Upgrade字段,其值为websocket。

现在我们将websocket的代码映射到servlet上去

  //将webSocket的地址映射到servlet上去    @Override      protected void doPost(HttpServletRequest req, HttpServletResponse resp)              throws ServletException, IOException {            ApplicationContext context = WebApplicationContextUtils                  .getWebApplicationContext(req.getServletContext());        //websocket的处理器        WebSocketHttpRequestHandler handler = new WebSocketHttpRequestHandler(                  context.getBean("myHandler", MyHandler.class));          //websocket的握手处理器        List<HandshakeInterceptor> interceptors = new ArrayList<HandshakeInterceptor>();          interceptors.add(context.getBean("myInterceptor",                  MyWebSocketHandshakeInterceptor.class));            handler.setHandshakeInterceptors(interceptors);            handler.handleRequest(req, resp);      }  


完整代码地址在:http://download.csdn.net/detail/u013803262/9899775


参考自:http://blog.csdn.net/aitangyong/article/details/50533414

阅读全文
0 0
原创粉丝点击