So, I'm not for sure what the problem is here, but I'm trying to create a simple server in Java, but whenever a client connects (I've been connecting via a localhost request from Google Chrome) the one single client connection will connect more than one time. (ie. every time I connect to my server via my browser the server prints "User connected successfully" 2-5 times.) I am not for sure how the main thread could possibly race back up to the top of the loop and connect to the same client more than once.
...
ServerSocket ss = new ServerSocket(9876);
while(true)
{
Socket s = ss.accept();
if(count >= queuesize || count >= numproducers)
{
System.out.println("Thread pool has reached it's limit. User access denied.");
//....
//error message sent to user here
//....
}
else
{
System.out.println("User connected successfully");
for(int x=0;x<numproducers;x++)
{
if(threads.get(position).isAvailable())
{
threads.get(x).start(s);
position = (position+1) % numproducers;
break;
}
position = (position+1) % numproducers;
}
}
}
Here is a workaround. It might help you.
Create a Set
or Map
containing hash code of all the connected Socket
from server at below line
Socket s = ss.accept();
Now check every time whenever a new client is trying to connect, if its a same Socket
then do nothing or close the socket.