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.