package com.sckj.common.socketio; import com.corundumstudio.socketio.SocketIOServer; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ObjectUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; /** * @Author: sckj * @Description: 客户端自动连接和断开、服务端关闭 */ @Component @Slf4j public class SocketHandler { @Autowired private SocketIOServer socketIoServer; private static final String USERID = "userId"; /** * 容器销毁前,自动调用此方法,关闭 socketIo 服务端 * * @Param [] * @return **/ @PreDestroy private void destroy(){ try { log.debug("关闭 socket 服务端"); if(null != socketIoServer){ socketIoServer.stop(); } }catch (Exception e){ e.printStackTrace(); } } @PostConstruct public void init() { log.debug("SocketEventListener initialized"); //添加监听,客户端自动连接到 socket 服务端 socketIoServer.addConnectListener(client -> { String userId = client.getHandshakeData().getSingleUrlParam(USERID); log.info("客户端userId: {},已连接,客户端ID为:{}",userId,client.getSessionId()); if(ObjectUtils.isNotEmpty(userId)){ SocketUtil.connectMap.put(userId, client); SocketUtil.clientUserIds.put(client,userId); } }); //添加监听,客户端跟 socket 服务端自动断开 socketIoServer.addDisconnectListener(client -> { String userId = client.getHandshakeData().getSingleUrlParam(USERID); log.info("客户端userId: {},断开连接,客户端ID为:{}",userId,client.getSessionId()); if(ObjectUtils.isNotEmpty(userId)){ SocketUtil.connectMap.remove(userId, client); SocketUtil.clientUserIds.remove(client,userId); } }); } }