packagecom.vcgeek.hephaestus.socketio;importcom.corundumstudio.socketio.SocketIOClient;importcom.corundumstudio.socketio.SocketIOServer;importcom.vcgeek.hephaestus.pojo.PushMessage;importorg.apache.commons.lang3.StringUtils;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;importjavax.annotation.PostConstruct;importjavax.annotation.PreDestroy;importjava.util.List;importjava.util.Map;importjava.util.Set;importjava.util.concurrent.ConcurrentHashMap;/*** 功能描述
*
*@author: zyu
* @description:
* @date: 2019/4/23 10:42*/@Service(value= "socketIOService")public class SocketIOServiceImpl implementsSocketIOService {//用来存已连接的客户端
private static Map clientMap = new ConcurrentHashMap<>();
@AutowiredprivateSocketIOServer socketIOServer;/*** Spring IoC容器创建之后,在加载SocketIOServiceImpl Bean之后启动
*
*@throwsException*/@PostConstructprivate void autoStartup() throwsException {
start();
}/*** Spring IoC容器在销毁SocketIOServiceImpl Bean之前关闭,避免重启项目服务端口占用问题
*
*@throwsException*/@PreDestroyprivate void autoStop() throwsException {
stop();
}
@Overridepublic void start() throwsException {//监听客户端连接
socketIOServer.addConnectListener(client ->{
String loginUserNum=getParamsByClient(client);if (loginUserNum != null) {
System.out.println(loginUserNum);
System.out.println("SessionId: " +client.getSessionId());
System.out.println("RemoteAddress: " +client.getRemoteAddress());
System.out.println("Transport: " +client.getTransport());
clientMap.put(loginUserNum, client);
}
});//监听客户端断开连接
socketIOServer.addDisconnectListener(client ->{
String loginUserNum=getParamsByClient(client);if (loginUserNum != null) {
clientMap.remove(loginUserNum);
System.out.println("断开连接: " +loginUserNum);
System.out.println("断开连接: " +client.getSessionId());
client.disconnect();
}
});//处理自定义的事件,与连接监听类似
socketIOServer.addEventListener("text", Object.class, (client, data, ackSender) ->{//TODO do something
client.getHandshakeData();
System.out.println(" 客户端:************ " +data);
});
socketIOServer.start();
}
@Overridepublic voidstop() {if (socketIOServer != null) {
socketIOServer.stop();
socketIOServer= null;
}
}
@Overridepublic voidpushMessageToUser(PushMessage pushMessage) {
String loginUserNum=pushMessage.getLoginUserNum();if(StringUtils.isNotBlank(loginUserNum)) {
SocketIOClient client=clientMap.get(loginUserNum);if (client != null)
client.sendEvent(PUSH_EVENT, pushMessage);
}
}/*** 此方法为获取client连接中的参数,可根据需求更改
*@paramclient
*@return
*/
privateString getParamsByClient(SocketIOClient client) {//从请求的连接中拿出参数(这里的loginUserNum必须是唯一标识)
Map> params =client.getHandshakeData().getUrlParams();
List list = params.get("loginUserNum");if (list != null && list.size() > 0) {return list.get(0);
}return null;
}public static MapgetClientMap() {returnclientMap;
}public static void setClientMap(MapclientMap) {
SocketIOServiceImpl.clientMap=clientMap;
}
}