2

I have a java.net.ServerSocket that is am using to listen for connections. I am using it's accept() method in order to obtain connections from clients and then handle them appropriately. I wish to continously be listening for clients and never be unavailable to them. Currently I have code similar to this:

ServerSocket serverSocket = ...
while (shouldBeListening) {
    handleClient(serverSocket.accept());
}

The handleClient method may take a small amount of time (less than a tenth of a millisecond). I am worried that between the time the ServerSocket.accept() method returns and it is called again that a request for a connection could have been missed. What is the best way to solve this issue?

EDIT: The way I am implementing it currently creates a new thread in the handleClient method, but even this takes time (especially since this is being run on a Raspberry Pi), I am worried that if a connection is requested while the handleClient method is being executed then it may be rejected because accept() is not being run.

Llew Vallis
  • 336
  • 3
  • 11

1 Answers1

5

Something like this.

 ServerSocket listener = new ServerSocket(8001);
    try {
      while (true) {
         Socket socket = listener.accept();

Then you can pass socket reference to the handler class you have. Make that class implements Runnable. Create a new thread each time you pass the socket reference to the handler class to handle the requests simultaneously. Please see the below links for solutions. If you need a full code. Let me know.

Runnable Sample by Jenkov

ThreadPool Sample - Stackoverflow

Kevin
  • 405
  • 1
  • 5
  • 21
  • Wouldn't this have the same problem? If a connection comes in and the accept method is returned from, what if another connection comes in before the JVM has the chance to call the accept method a second time? Even if I offload all of the main work to another thread, I still have to create and start a thread, which takes time. During that time, I may have missed a connection. – Llew Vallis Mar 19 '18 at 05:36
  • Valid question. Then you will have to queue the client requests. Or use a messaging service for accepting requests. – Kevin Mar 19 '18 at 05:42
  • Please check http://tutorials.jenkov.com/java-multithreaded-servers/thread-pooled-server.html – Kevin Mar 19 '18 at 05:43
  • Ok, the article suggests that it is not possible to always be accepting connections. It surprises me that there is not some way to always be listening for a connection, but I suppose I will just have to make sure clients retry connections in case the JVM was outside the accept method. Thanks for the help. – Llew Vallis Mar 19 '18 at 05:49
  • You are welcome. If you need to implement continues listening mechanism , you will have to try a different java technology. However, it is better retrying if clients receive any connection related exceptions. Also make sure the sever handles duplicate requests. – Kevin Mar 19 '18 at 09:05