Limit Connections with semaphores
Posted
by Robert
on Stack Overflow
See other posts from Stack Overflow
or by Robert
Published on 2010-04-16T13:06:33Z
Indexed on
2010/04/16
13:33 UTC
Read the original article
Hit count: 329
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
}
© Stack Overflow or respective owner