|
| 1 | +import java.io.IOException; |
| 2 | +import java.net.ServerSocket; |
| 3 | +import java.net.Socket; |
| 4 | +import java.util.concurrent.ExecutorService; |
| 5 | + |
| 6 | +// From http://tutorials.jenkov.com/java-multithreaded-servers/thread-pooled-server.html |
| 7 | + |
| 8 | +public class ThreadPoolServer implements Runnable { |
| 9 | + |
| 10 | + protected ServerSocket serverSocket; |
| 11 | + protected Thread runningThread; |
| 12 | + protected ExecutorService threadPool; |
| 13 | + |
| 14 | + |
| 15 | + protected int serverPort = 9000; |
| 16 | + protected boolean isStopped = false; |
| 17 | + |
| 18 | + public ThreadPoolServer(int port, ExecutorService threadPool) { |
| 19 | + this.serverPort = port; |
| 20 | + this.threadPool = threadPool; |
| 21 | + } |
| 22 | + |
| 23 | + @Override |
| 24 | + public void run() { |
| 25 | + synchronized(this) { |
| 26 | + this.runningThread = Thread.currentThread(); |
| 27 | + } |
| 28 | + this.openServerSocket(); |
| 29 | + while (! this.isStopped()) { |
| 30 | + Socket clientSocket = null; |
| 31 | + try { |
| 32 | + clientSocket = this.serverSocket.accept(); |
| 33 | + } catch (IOException e) { |
| 34 | + if (this.isStopped()) { |
| 35 | + break; |
| 36 | + } |
| 37 | + throw new RuntimeException("Error accepting client connection" + e); |
| 38 | + } |
| 39 | + this.threadPool.execute(new WorkerRunnable(clientSocket, "Thread Pooled Server")); |
| 40 | + } |
| 41 | + this.threadPool.shutdown(); |
| 42 | + System.out.println("Server Stopped"); |
| 43 | + } |
| 44 | + |
| 45 | + public synchronized void stop() { |
| 46 | + this.isStopped = true; |
| 47 | + try { |
| 48 | + this.serverSocket.close(); |
| 49 | + } catch (IOException e) { |
| 50 | + throw new RuntimeException("Error closing server", e); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + private synchronized boolean isStopped() { |
| 55 | + return this.isStopped; |
| 56 | + } |
| 57 | + |
| 58 | + private void openServerSocket() { |
| 59 | + try { |
| 60 | + this.serverSocket = new ServerSocket(this.serverPort); |
| 61 | + } catch (IOException e) { |
| 62 | + throw new RuntimeException("Cannot open port " + this.serverPort + ":" + e); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | +} |
0 commit comments