I'm trying to limit the number of connections my server will accept using semaphores, but when running, my code doesn't seem to make this restriction - am I using the semaphore correctly? eg. I have hardcoded the number of permit as 2, but I can connect an unlimited number of clients...
public class EServer implements Runnable {
private ServerSocket serverSocket;
private int numberofConnections = 0;
private Semaphore sem = new Semaphore(2);
private volatile boolean keepProcessing = true;
public EServer(int port)
throws IOException {
serverSocket = new ServerSocket(port);
}
@Override
public void run() {
while (keepProcessing) {
try {
sem.acquire();
Socket socket = serverSocket.accept();
process(socket, getNextConnectionNumber());
} catch (Exception e) {
} finally {
sem.release();
}
}
closeIgnoringException(serverSocket);
}
private synchronized int getNextConnectionNumber() {
return ++numberofConnections;
}
// processing related methods
}