Mam do stworzenia prosty serwer TCP na uczelnie. Obsługę zleceń zrealizowac w postaci FutureTask.
public class Server extends Thread{
JTextArea consol;
DefaultListModel<String> list;
ServerSocket srv;
ExecutorService exec;
Map<Integer,Future<Socket>> tasks;
public Server(int port, JTextArea consol,DefaultListModel<String> list){
try {
srv = new ServerSocket(port);
} catch (IOException e1) {
e1.printStackTrace();
}
this.consol = consol;
this.list = list;
exec = Executors.newCachedThreadPool();
tasks = new HashMap<>();
start();
}
public void run(){
consol.append("Start Server");
int counter = 0;
while(true){
try {
tasks.put(counter, exec.submit(new Task(srv.accept(),consol,counter)));
consol.append("Client no."+(counter)+" was connected\n");
list.addElement("Client no."+counter);
System.out.println(tasks);
counter++;
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void stopTask(int i){
System.out.println(i);
Future<Socket> task = tasks.get(i);
task.cancel(true);
}
}
a zadanie wyglada nastepujaco
public class Task implements Callable<Socket>{
Socket soc;
DataInputStream in;
DataOutputStream out;
JTextArea consol;
int id;
String actual;
public Task(Socket soc, JTextArea consol, int id){
this.soc = soc;
this.consol = consol;
this.id= id;
}
@Override
public Socket call() throws IOException {
in = new DataInputStream(soc.getInputStream());
out = new DataOutputStream(soc.getOutputStream());
while(true){
if(Thread.currentThread().isInterrupted()){
consol.append("Client no."+id+" was cancelled\n");
break;
}
consol.append("Client "+id+" send: "+in.readUTF()+"\n");
}
return soc;
}
}
Problem jest mianowicie taki że nie zawsze po cancel(true) wywoluje interrupted w zadaniu przez co nie zawsze moge go wyłaczyc przed jego skonczeniem.
Jak zmusic by zawsze po wywolaniu cancel(true). wychodzil mi z whila w tasku...