I'm trying to do the same task with thread pools and it works for around two cycles then the server stops inputting and outputting, I'm not sure what the problems is, please could someone advise me.
import java.net.*;
import java.io.*;
public class Client{
public static void main(String[] args)throws IOException{
Socket socket = new Socket("127.0.0.1",8976);
while(true){
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String read = reader.readLine();
PrintStream print = new PrintStream(socket.getOutputStream());
print.println(read);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String out = in.readLine();
System.out.println(out);
}
}
}
import java.io.*;
import java.net.*;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class Server implements Executor{
private static final Executor exec = Executors.newFixedThreadPool(2);
public static void main(String[] args)throws IOException{
ServerSocket serverSocket = new ServerSocket(8976);
while(true){
final Socket clientAccept = serverSocket.accept();
Runnable Task = new Runnable(){
@Override
public void run(){
try{
input(clientAccept);
output(clientAccept);
}catch(IOException e){
e.printStackTrace();
}
}
};
exec.execute(Task);
}
}
public static synchronized void input(Socket connection)throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String read = reader.readLine();
System.out.println(read);
}
public static synchronized void output(Socket connection)throws IOException{
BufferedReader out = new BufferedReader(new InputStreamReader(System.in));
String output = out.readLine();
PrintStream print = new PrintStream(connection.getOutputStream());
print.println(output);
}
@Override
public void execute(Runnable command) {
new Thread(command).start();
}
}