This repository has been archived on 2021-12-05. You can view files and clone it, but cannot push or open issues or pull requests.
envoy/src/main/java/envoy/server/ConnectionManager.java

80 lines
2.2 KiB
Java

package envoy.server;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.jenkov.nioserver.ISocketIdListener;
/**
* Project: <strong>envoy-server-standalone</strong><br>
* File: <strong>ConnectionManager.java</strong><br>
* Created: <strong>03.01.2020</strong><br>
*
* @author Kai S. K. Engelbart
* @since Envoy Server Standalone v0.1-alpha
*/
public class ConnectionManager implements ISocketIdListener {
/**
* Contains all socket IDs that have not yet performed a handshake / acquired
* their corresponding user ID.
*
* @since Envoy Server Standalone v0.1-alpha
*/
private Set<Long> pendingSockets = new HashSet<>();
/**
* Contains all socket IDs that have acquired a user ID as keys to these IDs.
*
* @since Envoy Server Standalone v0.1-alpha
*/
private Map<Long, Long> sockets = new HashMap<>();
private static ConnectionManager connectionManager = new ConnectionManager();
private ConnectionManager() {}
/**
* @return a singleton instance of this object
* @since Envoy Server Standalone v0.1-alpha
*/
public static ConnectionManager getInstance() { return connectionManager; }
@Override
public void socketCancelled(long socketId) {
if (!pendingSockets.remove(socketId))
sockets.entrySet().stream().filter(e -> e.getValue() == socketId).forEach(e -> sockets.remove(e.getValue()));
}
@Override
public void socketRegistered(long socketId) { pendingSockets.add(socketId); }
/**
* Associates a socket ID with a user ID.
*
* @param userId the user ID
* @param socketId the socket ID
* @since Envoy Server Standalone v0.1-alpha
*/
public void registerUser(long userId, long socketId) {
sockets.put(userId, socketId);
pendingSockets.remove(userId);
}
/**
* @param userId the ID of the user registered at the a socket
* @return the ID of the socket
* @since Envoy Server Standalone v0.1-alpha
*/
public long getSocketId(long userId) { return sockets.get(userId); }
/**
* @param userId the ID of the user to check for
* @return {@code true} if the user is online
* @since Envoy Server Standalone v0.1-alpha
*/
public boolean isOnline(long userId) { return sockets.containsKey(userId); }
}