Advertisement
Chiddix

IO Server

Dec 16th, 2012
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.76 KB | None | 0 0
  1. import java.io.DataInputStream;
  2. import java.io.DataOutputStream;
  3. import java.io.IOException;
  4. import java.net.ServerSocket;
  5. import java.net.Socket;
  6. import java.util.concurrent.ExecutorService;
  7. import java.util.concurrent.Executors;
  8.  
  9. public class Server implements Runnable {
  10.  
  11.     private ExecutorService executors;
  12.     private ServerSocket serverSocket;
  13.     private Thread thread;
  14.  
  15.     private volatile boolean running;
  16.  
  17.     public void init(int port) throws IOException {
  18.         this.setRunning(true);
  19.         this.executors = Executors.newFixedThreadPool(10);
  20.         this.serverSocket = new ServerSocket(port);
  21.         this.thread = new Thread(this);
  22.         this.thread.start();
  23.     }
  24.  
  25.     @Override
  26.     public void run() {
  27.         while (isRunning()) {
  28.             try {
  29.                 Socket socket = serverSocket.accept();
  30.                 Worker worker = new Worker(socket);
  31.                 executors.submit(worker);
  32.             } catch (IOException e) {
  33.                 e.printStackTrace();
  34.             }
  35.         }
  36.     }
  37.  
  38.     public Thread getThread() {
  39.         return thread;
  40.     }
  41.  
  42.     public boolean isRunning() {
  43.         return running;
  44.     }
  45.  
  46.     public void setRunning(boolean running) {
  47.         this.running = running;
  48.     }
  49.  
  50.     private class Worker implements Runnable {
  51.         private final Socket socket;
  52.        
  53.         private final DataInputStream in;
  54.         private final DataOutputStream out;
  55.  
  56.         public Worker(Socket socket) throws IOException {
  57.             this.socket = socket;
  58.             this.in = new DataInputStream(socket.getInputStream());
  59.             this.out = new DataOutputStream(socket.getOutputStream());
  60.         }
  61.  
  62.         public void run() {
  63.             try {
  64.                 while (isRunning()) {
  65.                     String request = in.readUTF();
  66.                     out.writeUTF(request);
  67.                 }
  68.             } catch (IOException e) {
  69.                 e.printStackTrace();
  70.             } finally {
  71.                 try {
  72.                     socket.close();
  73.                 } catch (IOException e) {
  74.                     e.printStackTrace();
  75.                 }
  76.             }
  77.         }
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement