1

I have an implementation where I listen to a port for events and do processing based on the input. I have kept it in a infinite loop. However it only works once and then I have to restart the program again. Does control never come back. Is this infinite loop a good idea?

Integer port = Integer.parseInt(Configuration.getProperty("Environment", "PORT"));
ServerSocket serverSocket = new ServerSocket(port);
LOG.info("Process Server listening on PORT: " + port);
while(true){            
    Socket socket = serverSocket.accept();
    new Thread(new ProcessEvent(socket)).start();
}
Michaël
  • 3,679
  • 7
  • 39
  • 64
avinashkr
  • 512
  • 1
  • 5
  • 20
  • 1
    'However it only works once and then i have to restart the program again.' I don't understand - it's an infinite loop. Why would it only 'work once'? Is the loop exiting because of an exception raised inside it? 'Is this infinite loop a good idea.' - sure, why not? Most non-trivial porcesses are 'infinite loops', else they would run out of code:) – Martin James Dec 17 '14 at 09:15
  • This program will execute indefinitely and accept any number of connections, subject to what happens in the `ProcessEvent` class that you haven't posted. Unclear what you're asking. – user207421 Dec 17 '14 at 09:42
  • in a nutshell i am reading a file and copying it to another folder Assuming no exception /error happen it finishes perfectly .The thread will automatically hand control back to above main block code OR does this infinite loop keep running irrespective of whether thread has completed or not and keeps blocking on socket.accept() – avinashkr Dec 17 '14 at 09:53
  • *Any* infinite loop keeps running indefinitely. That's a tautology. The only mystery here is why you think otherwise. – user207421 Dec 17 '14 at 10:30

1 Answers1

1

Once you started the thread that handle the client, you also need to loop on a read function, because after you read a message, you will need to read the next messages. The accept() will return only once per client connection. After the connection is opened, everything happen in the thread, until the connection is closed.

Looping on accept() is a good idea, but the spawned thread must not exit as long as your client is connected. If you intentionally close the connection, then it should be fine if you make sure it is handled correctly on both sides, and the client needs to reopen the connection for further communication.

ElderBug
  • 5,926
  • 16
  • 25