I have a small Client Server program which works fine. However, my server stops looping at this line of code:
Socket client = server.accept()
I don't want this to happen simply because there are other operations the server should handle.
Below I'll describe what I mean.
public class TimeServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(4000);
final List<Socket> clients = new ArrayList<>();
while (true) {
// Some code I need the server to keep on looping on it
System.out.println("Waiting for connection");
// accept connection
Socket client = server.accept();
System.out.println("Coneccted to: " + client.getPort());
// assign client to the handler
TimeHandler handler = new TimeHandler(client);
Thread t = new Thread(handler);
t.start();
clients.add(client);
System.out.println("Thread id: " + t.getId());
}
}
}
How can I skip the server.accept()
method? Because the program stops at it, continuously waiting for a connection from a Client. The code below this line:
Socket client = server.accept()
won't run unless, obviously, a connection has been made.
If this can't happen or if it is considered a bad practice, what's a better option I could use to achieve what I want above?
The way the server is meant to work is this one. What ever comes after the accept, should take care of one particular incomming connection, such as resolving the response, or spawning a new thread for that connection to be responded, or deleagate it to a ThreadPool worker to perfom the response, and then loop to wait for another conection to come in.
If there are other things to do you might think of opening different Threads for those other things.