0

I have a Server that can receive multiple request at the same time.

In my Server, I have to make some traitement and wait for response. This traitmenet is done by externe library so I don't how much should I wait.

So the Server looks like :

public class MyServer{


@Override
//method from the library
public void workonRequest(){
   //---
   response=[...] 
   
}

    public void listenRequest() {
        new Thread(() -> {
            while (true) {
                try {
                    socket = server.accept();
                    ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
                    ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
                    socket.setTcpNoDelay(true); //TODO : Not sure !
                    new Thread(() -> {
                        try {
                            handleRequest(input, output);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }).start();
                } catch (IOException ex) {
                    System.out.println(ex.getMessage());
                }
            }
        }).start();
    }

And the handle request method is :

    public void handleRequest(ObjectInputStream input, ObjectOutputStream output) throws IOException {
        try {
            while (true) {
            //forward the request to the library
            //work on it [means using the library and waiting]
            // return response 
           }
}

}

The response object is the result that I want return to the client

  1. How to deal with the problem of waiting for the answer?
  2. How can I make sure that there will be no problems when more than 2 clients send requests at the same time.

Thanks in advance

N.Omar
  • 29
  • 6

1 Answers1

0

How to deal with the problem of waiting for the answer ?###

Using while(true) can create issues because you are blocking the thread and opening sub thread and multi streams will make it more complex. There is easy way called reactive programming which handles this kind of multi-threaded issues easily, quarkus async solution and spring, if you still want to manage your sockets from java code you can use akka

How can I make sure that there will be no problems when more than 2 clients send requests at the same time.

That can be done by not blocking the main thread and If you manage to use reactive and/or async approach you will not have that problem.

Reference

ozkanpakdil
  • 3,199
  • 31
  • 48