469164578 / SpringMvcWebSocket

springmvc搭建websocket
0 stars 0 forks source link

SpringMVC WebSocket #1

Open 469164578 opened 7 years ago

469164578 commented 7 years ago

闲来无事研究了一下springmvc对接在这里记录下源代码以便于以后使用,springmvc搭建就不在此介绍了,spring版本是4.2.0 首先倒入springwebsocket的依赖包spring-messaging-4.2.0.RELEASE.jar和spring-websocket-4.2.0.RELEASE.jar springmvc所有版本jar地址

package madeinsmart.source.service; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @Configuration @EnableWebSocket//开启websocket public class WebSocketConfig implements WebSocketConfigurer{

@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    registry.addHandler(new WebSocketHander(),"/echo.jhtml").addInterceptors(new HandshakeInterceptor()).setAllowedOrigins("*"); //支持websocket 的访问链接
    registry.addHandler(new WebSocketHander(),"/sockjs/echo.jhtml").addInterceptors(new HandshakeInterceptor()).setAllowedOrigins("*").withSockJS(); //不支持websocket的访问链接

}

}

package madeinsmart.source.service;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.web.socket.WebSocketHandler;

public class HandshakeInterceptor implements org.springframework.web.socket.server.HandshakeInterceptor{

 //进入hander之前的拦截
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
    if (request instanceof ServletServerHttpRequest) {
        ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
        HttpSession session = servletRequest.getServletRequest().getSession(false);
        String userName = "userName";
        if (session != null) {
            //使用userName区分WebSocketHandler,以便定向发送消息
            userName = (String) session.getAttribute("WEBSOCKET_USERNAME");
        }
        map.put("WEBSOCKET_USERNAME",userName);
    }
    return true;
}

@Override
public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {

}

}

package madeinsmart.source.service;

import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map;

import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.WebSocketMessage; import org.springframework.web.socket.WebSocketSession;

public class WebSocketHander implements WebSocketHandler{

private static final Map<String,WebSocketSession>  allUsersession = new HashMap<String, WebSocketSession>();
//初次链接成功执行
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    System.out.println("链接成功......");
    String userName = (String) session.getAttributes().get("WEBSOCKET_USERNAME");
    allUsersession.put(userName, session);
}

//接受消息处理消息
@Override
public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
    System.out.println("接受消息处理消息.......");
    System.out.println("接收到的消息为"+webSocketMessage.getPayload());
}

@Override
public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
    String userName = (String) webSocketSession.getAttributes().get("WEBSOCKET_USERNAME");
    if(webSocketSession.isOpen()){
        webSocketSession.close();
    }
    System.out.println("链接出错,关闭链接......");
    allUsersession.remove(userName);
}

@Override
public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
    System.out.println("链接关闭......" + closeStatus.toString());
    String userName = (String) webSocketSession.getAttributes().get("WEBSOCKET_USERNAME");
    allUsersession.remove(userName);
}

@Override
public boolean supportsPartialMessages() {
    return false;
}
/**
 * 给所有在线用户发送消息
 *
 * @param message
 */
public void sendMessageToUsers(TextMessage message) {
    Iterator iterator = allUsersession.entrySet().iterator();
    if(iterator.hasNext()){
        Map.Entry entry = (Map.Entry) iterator.next(); 
        String key = (String) entry.getKey(); 
        WebSocketSession webSocketSession = allUsersession.get(key);
        try {
            webSocketSession.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 * 给某个用户发送消息
 *
 * @param userName
 * @param message
 */
public void sendMessageToUser(String userName, TextMessage message) {
    WebSocketSession webSocketSession = allUsersession.get(userName);
    try {
        webSocketSession.sendMessage(message);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
}

}

测试代码

<!DOCTYPE html>

webSocket测试

注意如果访问404的时候检查spring是否配置

469164578 commented 7 years ago

springmvcwebsocet记录