-1

Disclaimer: I'm fairly new to Java, so mabye it's a stupid question. Here we go.

I am writing a program that listens on a port, accepts a connection, does its thing, and closes the port.

I want this to run in it's own thread which handles the complete communication. So, ServerSocket.accept() would be started in the thread.

But how can I only spawn a thread if I need it? I can not know if I receive data if I didn't use ServerSocket.accept() yet, but if I do this in the main method, I will not be able to accept a new one while this one is open.

Some sample code omitting imports for clarity:

public class communicator implements Runnable{

       private ServerSocket server;
       private Socket socket;

       Thread t;

       communicator(ServerSocket server){
          this.server = server;

          t = new Thread(this,"MyThread");
          t.start();

       }

       public void run() {
           try {
               socket = server.accept();
               //do stuff
               socket.close();
           } catch (IOException ex) {
               Logger.getLogger(communicator.class.getName()).log(Level.SEVERE, null, ex);
           }
       }
}

and the main class:

public class test {
    private static ServerSocket server;
    private static Socket socket;

    public static void main(String[] args) throws IOException{
        server = new ServerSocket(123);
        communicator comm = new communicator(server);
    }
}

Or maybe I can use something like, "if one thread is active, provide a new one"?

Thx.

Arpton
  • 7
  • 4
  • Does this answer your question? [Creating the ServerSocket in a separate thread?](https://stackoverflow.com/questions/15541804/creating-the-serversocket-in-a-separate-thread) – Roger Gustavsson Nov 28 '19 at 15:08
  • I don't understand the question. If you spawn a thread that accepts sockets when needed, you won't be calling `accept()` in the main thread, so you won't have the problem you describe, so you already have the solution. So what's your question? – user207421 Nov 28 '19 at 20:04
  • I have one thread which accepts the connection. While this is open, I could get another request, but this could not be accepted, if there is no other thread that can accept it. So I need another thread for that, but I can not know if there is another request, so I would always need to provide a free thread, but since I dont know how many connections there will be, I would need to have a lot of threads ready, just in case. – Arpton Nov 29 '19 at 09:05

1 Answers1

0

You can use Threadpools and an ExecturonerService something like this.


public class Listener implements Runnable {

    private ServerSocket serverSocket;
    ExecutorService executorService = Executors.newCachedThreadPool();

    public Listener(ServerSocket serverSocket) {
        this.serverSocket = serverSocket;
    }

    @Override
    public void run() {
        try {
            while (true) {
                Socket accept = serverSocket.accept();
                executorService.execute(new Worker(accept));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

Listener waits until a connection comes, creates a new Worker object and gives it the executioner service to run it. This service will handle the number of threads that are needed for you und clean everything up when the task is done.

public class Worker implements Runnable{

    private Socket socket;

    public Worker(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        //do stuff
    }
}

Lira
  • 141
  • 2
  • 7
  • So, it is possible to do an accept (in the while loop) while another one is already active? That of course would solve it. And this seems to run without explicitly setting up threads manually? Thats nice. I'll try it. – Arpton Nov 29 '19 at 09:19
  • There is a little error, ServerListener should be the constructor, and therefor called Listener :) This works great, thanks! – Arpton Nov 29 '19 at 09:45
  • Yes. Everything that is in another thread will not be influenced by the accept. You can have as many threads as you want open at the same time. I would recommend you read some tutorials about thread pools and how they work. e.g. [link](https://howtodoinjava.com/java/multi-threading/java-thread-pool-executor-example/) – Lira Nov 29 '19 at 13:19
  • Great, Thank you! – Arpton Nov 29 '19 at 14:58