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.
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.