1. 添加jar包
javax.websocket javax.websocket-api 1.1 provided org.springframework spring-websocket 5.1.5.RELEASE org.springframework spring-messaging 5.1.5.RELEASE
2. 配置类
@EnableWebSocket@Configurationpublic class WebSocketConfig {// @Bean// public ServerEndpointExporter serverEndpointExporter() { // return new ServerEndpointExporter(); // } }
3 . 从websocket中获取用户session
public class HttpSessionConfigurator extends Configurator{ @Override public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { HttpSession httpSession = (HttpSession) request.getHttpSession(); sec.getUserProperties().put(HttpSession.class.getName(), httpSession); }}
4 . 设置监听
@WebListener@Componentpublic class RequestListener implements ServletRequestListener{ @Override public void requestDestroyed(ServletRequestEvent sre) { ServletRequestListener.super.requestDestroyed(sre); } @Override public void requestInitialized(ServletRequestEvent sre) { //将所有request请求都携带上httpSession ((HttpServletRequest) sre.getServletRequest()).getSession(); } public RequestListener() { }}
5. 获取spring容器工具类
@Component@Lazy(false)public class ApplicationContextRegister implements ApplicationContextAware { private static ApplicationContext APPLICATION_CONTEXT; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { APPLICATION_CONTEXT = applicationContext; } public static ApplicationContext getApplicationContext() { return APPLICATION_CONTEXT; }}
6. webSocket服务类
@Component@ServerEndpoint(value = "/onlineUser", configurator = HttpSessionConfigurator.class)public class WebSocketServer { //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 private static int onlineCount = 0; //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。 private static CopyOnWriteArraySetwebSocketSet = new CopyOnWriteArraySet (); //与某个客户端的连接会话,需要通过它来给客户端发送数据 private Session session; //用来存放在线用户 //private static CopyOnWriteArraySet