Advertisement
Chiddix

Basic NIO server

Jan 20th, 2013
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.95 KB | None | 0 0
  1. import java.io.IOException;
  2. import java.net.InetSocketAddress;
  3. import java.nio.channels.SelectionKey;
  4. import java.nio.channels.Selector;
  5. import java.nio.channels.ServerSocketChannel;
  6. import java.util.logging.Logger;
  7.  
  8. /**
  9.  * A server that accepts and handles connections.
  10.  */
  11. public class Server {
  12.    
  13.     /**
  14.      * The Logger of the server.
  15.      */
  16.     private static final Logger logger = Logger.getLogger(Server.class.getName());
  17.    
  18.     /**
  19.      * The Selector of the server.
  20.      */
  21.     private final Selector selector;
  22.    
  23.     /**
  24.      * The ServerSocketChannel of the server.
  25.      */
  26.     private final ServerSocketChannel serverSocketChannel;
  27.    
  28.     /**
  29.      * The running status of the server.
  30.      */
  31.     private volatile boolean running;
  32.  
  33.     /**
  34.      * Creates the server and configures the blocking.
  35.      *
  36.      * @throws IOException
  37.      */
  38.     public Server() throws IOException {
  39.         selector = Selector.open();
  40.         serverSocketChannel = ServerSocketChannel.open();
  41.         serverSocketChannel.configureBlocking(false);
  42.     }
  43.    
  44.     /**
  45.      * Binds the server to the specific hostname and port.
  46.      *
  47.      * @param hostname The hostname the server is binded to.
  48.      * @param port The port the server is binded to.
  49.      *
  50.      * @return The server instance.
  51.      *
  52.      * @throws IOException
  53.      */
  54.     public Server bind(final String hostname, final int port) throws IOException {
  55.         if (!serverSocketChannel.isOpen() || !selector.isOpen()) {
  56.             logger.info("Server has already been binded.");
  57.             return this;
  58.         }
  59.        
  60.         serverSocketChannel.bind(new InetSocketAddress(hostname, port));
  61.         serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
  62.         return this;
  63.     }
  64.    
  65.     /**
  66.      * Gets the running status of the server.
  67.      *
  68.      * @return The running status of the server.
  69.      */
  70.     public boolean isRunning() {
  71.         return running;
  72.     }
  73.  
  74.     /**
  75.      * Sets the running status of the server.
  76.      *
  77.      * @param running The running status of the server.
  78.      */
  79.     public void setRunning(final boolean running) {
  80.         this.running = running;
  81.     }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement