SpringMVC整合WebSocket实现即时通讯

1. pom中添加socket支持:

        
            org.springframework
            spring-websocket
            ${spring.version}
        

        
            org.springframework
            spring-messaging
            ${spring.version}
        

2.web.xml文件需要配置参数 async-supported 为 true


    Spring MVC Application

    
        mvc-dispatcher
        org.springframework.web.servlet.DispatcherServlet
        1
        true
    

    
        mvc-dispatcher
        *.html
    

3.创建对应的处理类, 用来处理消息

public class ChatSocket implements WebSocketHandler {

    private static final Logger log = LoggerFactory.getLogger(ChatSocket.class);

    private static WebSocketSession socketSession;
    private static Core core = Core.getInstance();
    private static UserInfo self = new UserInfo(core.getUserSelf());

    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        this.socketSession = webSocketSession;
    }

    @Override
    public void handleMessage(
            WebSocketSession webSocketSession,
            WebSocketMessage webSocketMessage) throws Exception {
        Map map = JacksonUtils.extractMap(webSocketMessage.getPayload().toString(), new HashMap<>());
        String content = map.get("content");
        String userName = map.get("userName");
        MessageTools.sendMsgById(content, userName);
        BaseMsg msg = new BaseMsg("text", content, content, core.getUserName(), userName, self);
        sendMsgToUser(msg);
    }

    @Override
    public void handleTransportError(
            WebSocketSession webSocketSession,
            Throwable throwable) throws Exception {

    }

    @Override
    public void afterConnectionClosed(
            WebSocketSession webSocketSession,
            CloseStatus closeStatus) throws Exception {

    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}

4.添加spring-websocket.xml文件



    
    

    
        
    

    
    
        
        
    
            

5.Spring中引入该配置文件

6.前端页面处理


$(function () {
    var websocket;

    // 首先判断是否 支持 WebSocket
    if ('WebSocket' in window) {
      websocket = new WebSocket("ws://localhost:8080/websocket.html");
    } else if ('MozWebSocket' in window) {
      websocket = new MozWebSocket("ws://localhost:8080/websocket.html");
    } else {
      websocket = new SockJS("http://localhost:8080/sockjs/websocket.html");
    }

    // 打开时
    websocket.onopen = function (evnt) {
      console.log("  websocket.onopen  ");
    };


    // 处理消息时
    websocket.onmessage = function (evnt) {
      $("#msg").append("

(" + evnt.data + ")

"); console.log(" websocket.onmessage "); }; websocket.onerror = function (evnt) { console.log(" websocket.onerror "); }; websocket.onclose = function (evnt) { console.log(" websocket.onclose "); }; $("#send_btn").click(function () { var text = $("#tx").val(); var msg = { msgContent: text, postsId: 1 }; websocket.send(JSON.stringify(msg)); }); });

7.配置完成, 调试

源码地址: Web微信, SpringMVC使用Socket做聊天链接

你可能感兴趣的:(java,WebSocket)