crashtest/src/de/ctdo/crashtest/Communication.java

74 lines
1.9 KiB
Java

package de.ctdo.crashtest;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Communication implements Runnable {
private final static int LISTEN_PORT = 2342;
private Boolean isStopped = false;
private ServerSocket serverSocket;
private Thread runningThread;
private ExecutorService threadPool = Executors.newFixedThreadPool(10);
private GuiControl control;
public Communication(GuiControl control) {
this.control = control;
}
private synchronized boolean isStopped() {
return this.isStopped;
}
@Override
public void run() {
synchronized(this){
this.runningThread = Thread.currentThread();
}
openServerSocket();
while(!isStopped()){
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
} catch (IOException e) {
if(isStopped()) {
System.out.println("Server Stopped.") ;
return;
}
throw new RuntimeException("Error accepting client connection", e);
}
this.threadPool.execute(new CommunicationRunner(clientSocket, this.control));
}
this.threadPool.shutdown();
System.out.println("Server Stopped.") ;
}
public synchronized void stop() {
this.isStopped = true;
try {
this.serverSocket.close();
} catch (IOException e) {
throw new RuntimeException("Error closing server", e);
}
}
private void openServerSocket() {
try {
this.serverSocket = new ServerSocket(LISTEN_PORT);
} catch (IOException e) {
throw new RuntimeException("Cannot open port 8080", e);
}
}
}