0
votes

I'm creating a simple http server. I have a master thread that waits in a loop for a connection to be accepted. Once a connection is accepted, I create a new worker thread to handle the connection, passing the accepted socket as an argument. Once a connection is accepted, a new thread is created for it, however the master thread will loop again, create another socket with the same connection and create another duplicated thread.

Master thread waiting for connections.

public void run(){
    while(Tester.serverStatus != "quit"){
    try {
        Socket clientSocket = serverSocket.accept();
        new Thread(new Worker(clientSocket)).start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
    try {
        this.stop();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return;
}

public void stop() throws IOException{
    serverSocket.close();
    return;

}

Worker thread pseudocode

            public void run(){
InputStream input = clientSocket.getInputStream();
//read from stream, validate request and setup the response in a byte array
input.close();

DataOutputStream output = new DataOutputStream(clientSocket.getOutputStream());
output.write(responseByteArray);
output.flush();
output.close();

clientSocket.close();
return;


}

Any ideas as to why the accept() method isn't being blocked after the first connection is accepted? It just keeps on creating duplicate Worker threads with the same Socket.

Thanks

1
It's not really possible to create fully duplicate connections with sockets API. Are you sure you are not spinning on the client around the connect call? Check the connections source port numbers with netstat. - Nikolai Fetissov

1 Answers

0
votes

What you describe is not possible.

You undoubtedly have some static variables somewhere that should be instance members of Worker, such as the input and/or output streams, and/or the socket itself.