springmvc4使用websocket

spring mvc 4中使用websocket
1.spring-servlet.xml中需要配置websocket

<bean id="websocket" class="com.springmvc.utils.MyWebSocketHandler"/> 
       <websocket:handlers>
           <!-配置映射路径->
           <websocket:mapping path="/webSocket" handler="websocket"/>
           <websocket:handshake-interceptors>
               <bean class="org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor"/>
           </websocket:handshake-interceptors>
       </websocket:handlers>

2.com.springmvc.utils包中创建MyWebSocketHandler类

package com.springmvc.utils;

import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * WebSocket的处理类,用于前端与后台之间的双端通信
 * 
 * @author caixiaocong
 */
public class MyWebSocketHandler extends TextWebSocketHandler implements WebSocketHandler {

    private static final Log log =  LogFactory.getLog(MyWebSocketHandler.class);

    WebSocketSession session;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        this.session = session;
        log.info("webSocket connect.");
    }

    // handle message receive
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        try {
            session.sendMessage(new TextMessage("hello"));  
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // send message
    public void sendMessage() throws IOException{
        if(session!=null && session.isOpen()){
            session.sendMessage(new TextMessage("hello"));
            log.info("webSocket send message");
        }
    }

}  

3.js中使用websocket

$(document).ready(function() {
        //webSocke
        var hostport = document.location.host;
        var socketurl = 'ws://' + hostport + '/Satellite/webSocket';
        var ws = new WebSocket(socketurl);
        /* ws.onopen = function() { 
            alert('webSocket connet');
        };  */
        ws.onmessage = function(event) {
            /*这里写websocket中获取到新的消息时候的处理方法*/
        };
        /* ws.onerror = function() {
            alert('webSocket连接失败'); 
        }; */
    });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值