Example usage for java.net ServerSocket ServerSocket

List of usage examples for java.net ServerSocket ServerSocket

Introduction

In this page you can find the example usage for java.net ServerSocket ServerSocket.

Prototype

public ServerSocket(int port, int backlog) throws IOException 

Source Link

Document

Creates a server socket and binds it to the specified local port number, with the specified backlog.

Usage

From source file:Main.java

public Main() throws IOException {
    serverSocket = new ServerSocket(8008, 1000);
    serverSocket.setSoTimeout(10000);

}

From source file:Main.java

public Main() throws IOException {
    serverSocket = new ServerSocket(8008, 1000);
    serverSocket.setSoTimeout(10000);/*from   w w w . ja va  2s  .  c om*/

    serverSocket.bind(InetSocketAddress.createUnresolved("java2s.com", 8080), 1000);
}

From source file:jetbrains.exodus.util.ForkSupportIO.java

protected ForkSupportIO(@NotNull final String name, @NotNull String[] jvmArgs, @NotNull String[] args)
        throws IOException {
    try {/*from   ww  w  .  j  a va  2 s .c o m*/
        serverSocket = new ServerSocket(0, 10);
        log.info("Listening on port: " + serverSocket.getLocalPort());
    } catch (IOException e) {
        log.fatal("Failed to open server socket.", e);
        throw e;
    }
    this.name = name;

    // static does not suite here since System.getProperty result can vary
    final String javaHome = System.getProperty("java.home");
    if (javaHome == null || javaHome.length() == 0) {
        throw new IllegalStateException("java.home is undefined");
    }
    final File bin = new File(javaHome, "bin");
    File javaFile = new File(bin, "java");
    if (!(javaFile.exists() && javaFile.isFile())) {
        javaFile = new File(bin, "java.exe");
        if (!(javaFile.exists() && javaFile.isFile())) {
            throw new IllegalStateException(javaFile.getPath() + " doesn't exist");
        }
    }

    final String classpath = join(getClasspath(getClass()), File.pathSeparator);
    final String[] commonJvmArgs = { javaFile.getPath(),
            // "-Xdebug", "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=7777",
            "-cp", classpath };

    final List<String> trueArgs = new ArrayList<>();
    trueArgs.addAll(Arrays.asList(commonJvmArgs));
    trueArgs.addAll(Arrays.asList(jvmArgs));
    trueArgs.add(ForkedProcessRunner.class.getName());
    trueArgs.add(Integer.toString(serverSocket.getLocalPort()));
    trueArgs.add(name);
    trueArgs.addAll(Arrays.asList(args));

    log.info("Ready to start process with arguments: " + trueArgs);
    builder = new ProcessBuilder(trueArgs);
}

From source file:dk.netarkivet.common.utils.SystemUtils.java

/** Check that a given port is not in use.  If this method returns
 * normally, the port is safe to bind./*from w  ww .j  a v a 2 s.  c  om*/
 *
 * @param port Port to check
 * @throws IOFailure if the port cannot be bound.
 */
public static void checkPortNotUsed(int port) {
    try {
        ServerSocket s = new ServerSocket(port, 1);
        s.close();
    } catch (BindException e) {
        throw new IOFailure("Port " + port + " already in use, or " + "port is out of range", e);
    } catch (IOException e) {
        throw new IOFailure("IO error testing port " + port, e);
    }
}

From source file:com.linuxbox.enkive.server.AbstractSocketServer.java

public void run() {
    Socket sessionSocket = null;/*from   w  w w. ja va 2 s  .  co m*/
    boolean hasSocket = false;
    try {
        serverSocket = new ServerSocket(port, LISTEN_BACKLOG);
        serverSocket.setReceiveBufferSize(8);
        hasSocket = true;

        while (!hasShutdown()) {
            // TODO Eric : change this so there's a timeout and we can shut
            // down more cleanly than closing sockets out from under a
            // thread
            sessionSocket = serverSocket.accept(); // wait for connection

            // got connection!

            sessionSocket.setTcpNoDelay(true);

            createAndStartProcessor(sessionSocket);
            if (LOGGER.isTraceEnabled())
                LOGGER.trace(serviceName + " processor/session started");
        }
    } catch (SocketException e) {
        // will get a SocketException when the server socket is closed
        // LOGGER.debug("SocketException", e); catch it separately so it
        // isn't caught below in the catch for general exceptions
        if (!hasSocket) {
            LOGGER.error("unexpected socket exception", e);
        }
    } catch (Exception e) {
        LOGGER.error("Error running server or launching session.", e);
    } catch (Throwable e) {
        LOGGER.fatal("Unexpected error in server thread.", e);
    } finally {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace(serviceName + " server has left run loop");
        }
    }

    shutdownProcessors();
}

From source file:net.sf.firemox.network.Server.java

/**
 * If this thread was constructed using a separate <code>Runnable</code> run
 * object, then that <code>Runnable</code> object's <code>run</code>
 * method is called; otherwise, this method does nothing and returns.
 * <p>//from  www . j  av  a2s .c  o  m
 * Subclasses of <code>Thread</code> should override this method.
 * 
 * @see java.lang.Thread#start()
 * @see java.lang.Thread#Thread(java.lang.ThreadGroup, java.lang.Runnable,
 *      java.lang.String)
 * @see java.lang.Runnable#run()
 */
@Override
public void run() {
    // Creating connection socket
    try {
        serverSocket = new ServerSocket(port, 1);
        // enable timeout
        serverSocket.setSoTimeout(2000);

        // accept any client
        clientSocket = null;
        LoaderConsole.beginTask(LanguageManager.getString("wiz_network.creatingconnection"), 2);
        while (clientSocket == null && !cancelling) {
            try {
                clientSocket = serverSocket.accept();
            } catch (SocketException timeout) {
                if (!"socket closed".equals(timeout.getMessage())) {
                    throw timeout;
                }
            } catch (SocketTimeoutException timeout) {
                /*
                 * timeout of 'accept()' method, nothing to do, we look if we're still
                 * running
                 */
            }
        }

        // stopping?
        if (cancelling) {
            Log.info(LanguageManager.getString("wiz_network.canceledcreation"));
            cancelConnexion();
            return;
        }

        // A client is connecting...
        LoaderConsole.beginTask(LanguageManager.getString("wiz_network.incomming") + " : "
                + clientSocket.getInetAddress().toString(), 5);

        // free these two sockets later
        outBin = clientSocket.getOutputStream();
        inBin = clientSocket.getInputStream();
        // socketListener = new SocketListener(inBin);

        if (passwd != null && passwd.length > 0) {
            // a password is needed to connect to this server
            MToolKit.writeString(outBin, STR_PASSWD);
            if (MToolKit.readString(inBin).equals(new String(passwd))) {
                MToolKit.writeString(outBin, STR_OK);
            } else {
                // wrong password, this client client will be disconnected
                MToolKit.writeString(outBin, STR_WRONGPASSWD);
                // close stream
                IOUtils.closeQuietly(inBin);
                IOUtils.closeQuietly(outBin);
                // free pointers
                outBin = null;
                inBin = null;
            }
        } else {
            MToolKit.writeString(outBin, STR_OK);
        }

        // check version of client
        String clientVersion = MToolKit.readString(inBin);
        if (IdConst.VERSION.equals(clientVersion)) {
            MToolKit.writeString(outBin, STR_OK);
        } else {
            // two different versions
            MToolKit.writeString(outBin, STR_WRONGVERSION);
            LoaderConsole.beginTask(LanguageManager.getString("wiz_network.differentversionClientpb") + " ("
                    + clientVersion + ")", 10);
            IOUtils.closeQuietly(inBin);
            IOUtils.closeQuietly(outBin);
            // free pointers
            outBin = null;
            inBin = null;
        }

        if (outBin != null) {

            // enter in the main loop
            // Opponent is ...
            String clientName = MToolKit.readString(inBin);
            LoaderConsole.beginTask(LanguageManager.getString("wiz_network.opponentis") + clientName, 10);
            // I am ...
            MToolKit.writeString(outBin, nickName);

            // exchange shared string settings
            ((You) StackManager.PLAYERS[0]).sendSettings(outBin);
            ((Opponent) StackManager.PLAYERS[1]).readSettings(clientName, nickName, inBin);

            // stopping?
            if (cancelling) {
                cancelConnexion();
                return;
            }

            // set and send the random seed
            long seed = MToolKit.random.nextLong();
            MToolKit.random.setSeed(seed);
            MToolKit.writeString(outBin, Long.toString(seed));
            Log.info("Seed = " + seed);

            // write mana use option
            PayMana.useMana = Configuration.getBoolean("useMana", true);
            MToolKit.writeString(outBin, PayMana.useMana ? "1" : "0");

            // write opponent response option
            WaitActivatedChoice.opponentResponse = Configuration.getBoolean("opponnentresponse", true);
            MToolKit.writeString(outBin, WaitActivatedChoice.opponentResponse ? "1" : "0");

            // Who starts?
            final StartingOption startingOption = StartingOption.values()[Configuration.getInt("whoStarts",
                    StartingOption.random.ordinal())];
            MToolKit.writeString(outBin, String.valueOf(Configuration.getInt("whoStarts", 0)));
            final boolean serverStarts;
            switch (startingOption) {
            case random:
            default:
                serverStarts = MToolKit.random.nextBoolean();
                break;
            case server:
                serverStarts = true;
                break;
            case client:
                serverStarts = false;
            }

            if (serverStarts) {
                // server begins
                LoaderConsole.beginTask(LanguageManager.getString("wiz_network.youwillstarts") + " (mode="
                        + startingOption.getLocaleValue() + ")", 15);
                StackManager.idActivePlayer = 0;
                StackManager.idCurrentPlayer = 0;
            } else {
                // client begins
                LoaderConsole.beginTask(LanguageManager.getString("wiz_network.opponentwillstart") + " (mode="
                        + startingOption.getLocaleValue() + ")", 15);
                StackManager.idActivePlayer = 1;
                StackManager.idCurrentPlayer = 1;
            }

            // load rules from the MDB file
            dbStream = MdbLoader.loadMDB(MToolKit.mdbFile, StackManager.idActivePlayer);
            TableTop.getInstance().initTbs();

            // receive and validate her/his deck
            LoaderConsole.beginTask(LanguageManager.getString("wiz_network.receivingdeck"), 25);
            readAndValidateOpponentDeck();

            // stopping?
            if (cancelling) {
                cancelConnexion();
                return;
            }

            // send our deck
            LoaderConsole.beginTask(LanguageManager.getString("wiz_network.sendingdeck"), 55);
            deck.send(outBin);
            StackManager.PLAYERS[0].zoneManager.giveCards(deck, dbStream);

            // stopping?
            if (cancelling) {
                cancelConnexion();
                return;
            }

            MToolKit.writeString(outBin, "%EOF%");

            // free resources
            outBin.flush();

            // stopping?
            if (cancelling) {
                cancelConnexion();
                return;
            }

            initBigPipe();
            MagicUIComponents.magicForm.initGame();
        }
    } catch (Throwable e) {
        NetworkActor.cancelling = true;
        LoaderConsole.endTask();
        cancelConnexion();
        JOptionPane.showMessageDialog(MagicUIComponents.magicForm,
                LanguageManager.getString("wiz_server.error") + " : " + e.getMessage(),
                LanguageManager.getString("error"), JOptionPane.WARNING_MESSAGE);
        Log.error(e);
        return;
    }
}

From source file:org.eclipse.oomph.internal.util.HTTPServer.java

public HTTPServer(int minPort, int maxPort) throws IOException {
    addContext(IMAGE_CONTEXT);/*www.j  a  v a 2  s  .c o m*/

    for (int port = minPort; port <= maxPort; port++) {
        try {
            ServerSocket serverSocket = new ServerSocket(port, 500);
            acceptor = new Acceptor(serverSocket);
            return;
        } catch (BindException ex) {
            // Try next port.
        } catch (InterruptedException ex) {
            throw new IOExceptionWithCause("Start interrupted", ex);
        }
    }

    throw new IOException("No port available between " + minPort + " and " + maxPort);
}

From source file:com.adaptris.http.HttpListener.java

/**
 * @see Listener#initialise()//from www  .j a  v  a 2s  .c om
 */
public void initialise() throws HttpException {
    if (initialised) {
        return;
    }
    try {
        if (serverSocket == null) {
            serverSocket = new ServerSocket(listenPort, 1024);
            if (logR.isTraceEnabled()) {
                logR.trace("Server socket timeout set to " + serverSocketTimeout + "ms");
            }
            serverSocket.setSoTimeout(serverSocketTimeout);
            if (logR.isInfoEnabled()) {
                logR.info("Initialised to listen for HTTP connections on port " + serverSocket.getLocalPort());
            }
            listenPort = serverSocket.getLocalPort();
        }
        initialised = true;
    } catch (Exception e) {
        throw new HttpException(e);
    }
}

From source file:net.wimpi.telnetd.net.PortListener.java

/**
 * Listen constantly to a server socket and handles incoming connections
 * through the associated {a:link ConnectionManager}.
 *
 * @see net.wimpi.telnetd.net.ConnectionManager
 *///from w w w  . j  a  v  a2  s .com
public void run() {
    try {
        /*
            A server socket is opened with a connectivity queue of a size specified
            in int floodProtection.  Concurrent login handling under normal circumstances
            should be handled properly, but denial of service attacks via massive parallel
            program logins should be prevented with this.
        */
        m_ServerSocket = new ServerSocket(m_Port, m_FloodProtection);

        //log entry
        Object[] args = { new Integer(m_Port), new Integer(m_FloodProtection) };
        log.info(MessageFormat.format(logmsg, args));

        do {
            try {
                Socket s = m_ServerSocket.accept();
                if (m_Available) {
                    connectionManager.makeConnection(s);
                } else {
                    //just shut down the socket
                    s.close();
                }
            } catch (SocketException ex) {
                if (m_Stopping) {
                    //server socket was closed blocked in accept
                    log.debug("run(): ServerSocket closed by stop()");
                } else {
                    log.error("run()", ex);
                }
            }
        } while (!m_Stopping);

    } catch (IOException e) {
        log.error("run()", e);
    }
    log.debug("run(): returning.");
}

From source file:com.mirth.connect.connectors.tcp.TcpMessageReceiver.java

protected ServerSocket createSocket(URI uri) throws IOException {
    String host = uri.getHost();/* w w  w. j a va2 s . c  o  m*/
    int backlog = connector.getBacklog();
    if (host == null || host.length() == 0) {
        host = "localhost";
    }
    InetAddress inetAddress = InetAddress.getByName(host);
    if (inetAddress.equals(InetAddress.getLocalHost()) || inetAddress.isLoopbackAddress()
            || host.trim().equals("localhost")) {
        return new ServerSocket(uri.getPort(), backlog);
    } else {
        return new ServerSocket(uri.getPort(), backlog, inetAddress);
    }
}