Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.IOException;
- import java.net.InetSocketAddress;
- import java.nio.channels.SelectionKey;
- import java.nio.channels.Selector;
- import java.nio.channels.ServerSocketChannel;
- import java.util.logging.Logger;
- /**
- * A server that accepts and handles connections.
- */
- public class Server {
- /**
- * The Logger of the server.
- */
- private static final Logger logger = Logger.getLogger(Server.class.getName());
- /**
- * The Selector of the server.
- */
- private final Selector selector;
- /**
- * The ServerSocketChannel of the server.
- */
- private final ServerSocketChannel serverSocketChannel;
- /**
- * The running status of the server.
- */
- private volatile boolean running;
- /**
- * Creates the server and configures the blocking.
- *
- * @throws IOException
- */
- public Server() throws IOException {
- selector = Selector.open();
- serverSocketChannel = ServerSocketChannel.open();
- serverSocketChannel.configureBlocking(false);
- }
- /**
- * Binds the server to the specific hostname and port.
- *
- * @param hostname The hostname the server is binded to.
- * @param port The port the server is binded to.
- *
- * @return The server instance.
- *
- * @throws IOException
- */
- public Server bind(final String hostname, final int port) throws IOException {
- if (!serverSocketChannel.isOpen() || !selector.isOpen()) {
- logger.info("Server has already been binded.");
- return this;
- }
- serverSocketChannel.bind(new InetSocketAddress(hostname, port));
- serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
- return this;
- }
- /**
- * Gets the running status of the server.
- *
- * @return The running status of the server.
- */
- public boolean isRunning() {
- return running;
- }
- /**
- * Sets the running status of the server.
- *
- * @param running The running status of the server.
- */
- public void setRunning(final boolean running) {
- this.running = running;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement