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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值