This task can be easily done using WebSockets. Below there is required application code written using Bristleback Server (assuming that the check is performed when new user is connecting).
@Component
public class CountUsersConnectionListeners implements ConnectionStateListener<DefaultUser> {
private static final int MAGIC_MAXIMUM_NUMBER_OF_USERS = 2;
private int numberOfCurrentlyConnected;
@Autowired
private ConnectionCountClientClass connectionCountClientClass;
@Override
public void userConnected(DefaultUser defaultUser) {
if (numberOfCurrentlyConnected > MAGIC_MAXIMUM_NUMBER_OF_USERS) {
connectionCountClientClass.showButtonToNewUser(defaultUser);
numberOfCurrentlyConnected++;
return;
}
numberOfCurrentlyConnected++;
if (numberOfCurrentlyConnected > MAGIC_MAXIMUM_NUMBER_OF_USERS) {
connectionCountClientClass.showButton(true);
}
}
@Override
public void userDisconnected(DefaultUser defaultUser) {
if (numberOfCurrentlyConnected <= MAGIC_MAXIMUM_NUMBER_OF_USERS) {
numberOfCurrentlyConnected--;
return;
}
numberOfCurrentlyConnected--;
if (numberOfCurrentlyConnected <= MAGIC_MAXIMUM_NUMBER_OF_USERS) {
connectionCountClientClass.hideButton(true);
}
}
}
Note that this is just a prototype, I did not care about synchronization and the code where actual number of connected users is set could be placed elsewhere.
@ClientActionClass
@Component
public class ConnectionCountClientClass {
@ClientAction
public SendCondition showButton(boolean show) {
return AllUsersCondition.getInstance(); // this will send a message to all connected users
}
@ClientAction
public SendCondition hideButton(boolean hide) {
return AllUsersCondition.getInstance(); // this will send a message to all connected users
}
@ClientAction
public DefaultUser showButtonToNewUser(DefaultUser defaultUser) {
return defaultUser; // this will send a message only to the user given as parameter
}
}
Client side (only additional application code presented):
var sampleClientAction = {
showButton: function() {
alert("Show button!");
},
showButtonToNewUser: function() {
alert("Show me button!");
},
hideButton: function() {
alert("Hide button!");
}
};
dataController.registerClientActionClass("ConnectionCountClientClass", sampleClientAction);
If you're interested, I can send you entire working application [Maven required]. Jetty or Tomcat can be used as web application containers.