So what you want is something like the following
public class MyServerSocket {
int state = 0;
public static void main(String[] args) {
new MyServerSocket();
}
public MyServerSocket() {
try {
init();
} catch (IOException ex) {
Logger.getLogger(MyServerSocket.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void init() throws IOException {
int portNumber = 4444;
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));) {
MyReadThread mrt = new MyReadThread(this, in);
Thread t = new Thread(mrt);
t.start();
int maxAwake = 10;
int i = 0;
while(state == 0 && !(i>maxAwake)){
Thread.sleep(1000);
i++;
Logger.getLogger(MyServerSocket.class.getName()).info("awake and asleep");
}
Logger.getLogger(MyServerSocket.class.getName()).info("awake counter: " + i);
out.println("Good bye");
out.close();
in.close();
clientSocket.close();
serverSocket.close();
} catch (InterruptedException ex) {
Logger.getLogger(MyServerSocket.class.getName()).log(Level.SEVERE, null, ex);
}
}
where the Thread is reading the input in the following way
public class MyReadThread implements Runnable {
BufferedReader in = null;
MyServerSocket caller = null;
public MyReadThread(MyServerSocket caller, BufferedReader in) {
this.in = in;
this.caller = caller;
}
@Override
public void run() {
if (in == null || caller == null) {
throw new RuntimeException("Input stream or caller server socket is null");
}
String inputLine = "";
boolean quit = false;
while (!quit) {
try {
inputLine = in.readLine();
} catch (IOException e) {
if (e instanceof SocketException){
inputLine = null;
}
else{
Logger.getLogger(MyServerSocket.class.getName()).log(Level.SEVERE, null, e);
}
}
if (inputLine == null) {
Logger.getLogger(MyServerSocket.class.getName()).warning("Client suddenly disconnected");
quit = true;
caller.state = 1;
}
Logger.getLogger(MyServerSocket.class.getName()).info("input line over connection is: " + inputLine);
if ("quit".equals(inputLine)) {
quit = true;
caller.state = 2;
}
}
}
}
This is just a sketch, of course. Notice that you are not using NIO, Channels nor Selectors…
A similar question was asked here
Checking for a client disconnect on a Java TCP server - output only
But in that case no thread were used. In this case your main socket is actually sleeping until maxAwake while the thread is reading what you are sending...