Example usage for java.net ServerSocket close

List of usage examples for java.net ServerSocket close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this socket.

Usage

From source file:VASSAL.launch.TilingHandler.java

protected void runSlicer(List<String> multi, final int tcount, int maxheap)
        throws CancellationException, IOException {

    final InetAddress lo = InetAddress.getByName(null);
    final ServerSocket ssock = new ServerSocket(0, 0, lo);

    final int port = ssock.getLocalPort();

    final List<String> args = new ArrayList<String>();
    args.addAll(Arrays.asList(new String[] { Info.javaBinPath, "-classpath",
            System.getProperty("java.class.path"), "-Xmx" + maxheap + "M", "-DVASSAL.id=" + pid,
            "-Duser.home=" + System.getProperty("user.home"), "-DVASSAL.port=" + port,
            "VASSAL.tools.image.tilecache.ZipFileImageTiler", aname, cdir.getAbsolutePath(),
            String.valueOf(tdim.width), String.valueOf(tdim.height) }));

    // get the progress dialog
    final ProgressDialog pd = ProgressDialog.createOnEDT(ModuleManagerWindow.getInstance(),
            "Processing Image Tiles", " ");

    // set up the process
    final InputStreamPump outP = new InputOutputStreamPump(null, System.out);
    final InputStreamPump errP = new InputOutputStreamPump(null, System.err);

    final ProcessWrapper proc = new ProcessLauncher().launch(null, outP, errP,
            args.toArray(new String[args.size()]));

    // write the image paths to child's stdin, one per line
    PrintWriter stdin = null;//  ww  w .  ja v  a2  s .c om
    try {
        stdin = new PrintWriter(proc.stdin);
        for (String m : multi) {
            stdin.println(m);
        }
    } finally {
        IOUtils.closeQuietly(stdin);
    }

    Socket csock = null;
    DataInputStream in = null;
    try {
        csock = ssock.accept();
        csock.shutdownOutput();

        in = new DataInputStream(csock.getInputStream());

        final Progressor progressor = new Progressor(0, tcount) {
            @Override
            protected void run(Pair<Integer, Integer> prog) {
                pd.setProgress((100 * prog.second) / max);
            }
        };

        // setup the cancel button in the progress dialog
        EDT.execute(new Runnable() {
            public void run() {
                pd.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        pd.setVisible(false);
                        proc.future.cancel(true);
                    }
                });
            }
        });

        boolean done = false;
        byte type;
        while (!done) {
            type = in.readByte();

            switch (type) {
            case STARTING_IMAGE:
                final String ipath = in.readUTF();

                EDT.execute(new Runnable() {
                    public void run() {
                        pd.setLabel("Tiling " + ipath);
                        if (!pd.isVisible())
                            pd.setVisible(true);
                    }
                });
                break;

            case TILE_WRITTEN:
                progressor.increment();

                if (progressor.get() >= tcount) {
                    pd.setVisible(false);
                }
                break;

            case TILING_FINISHED:
                done = true;
                break;

            default:
                throw new IllegalStateException("bad type: " + type);
            }
        }

        in.close();
        csock.close();
        ssock.close();
    } catch (IOException e) {

    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(csock);
        IOUtils.closeQuietly(ssock);
    }

    // wait for the tiling process to end
    try {
        final int retval = proc.future.get();
        if (retval != 0) {
            throw new IOException("return value == " + retval);
        }
    } catch (ExecutionException e) {
        // should never happen
        throw new IllegalStateException(e);
    } catch (InterruptedException e) {
        // should never happen
        throw new IllegalStateException(e);
    }
}

From source file:com.kodemore.utility.Kmu.java

/**
 * Call e.close, but wrap the call in a try/catch block
 * that logs any exception without throwing it.
 *//*w  w  w. j  a va  2  s  .  c  om*/
public static void closeSafely(ServerSocket e) {
    try {
        if (e != null)
            e.close();
    } catch (Exception ex) {
        KmLog.error(ex, "Cannot close socket.");
    }
}

From source file:org.jibble.pircbot.PircBot.java

/**
 * Attempts to establish a DCC CHAT session with a client.  This method
 * issues the connection request to the client and then waits for the
 * client to respond.  If the connection is successfully made, then a
 * DccChat object is returned by this method.  If the connection is not
 * made within the time limit specified by the timeout value, then null
 * is returned.//from ww  w .ja v  a 2 s .  com
 * <p/>
 * It is <b>strongly recommended</b> that you call this method within a new
 * Thread, as it may take a long time to return.
 * <p/>
 * This method may not be overridden.
 *
 * @param nick    The nick of the user we are trying to establish a chat with.
 * @param timeout The number of milliseconds to wait for the recipient to
 *                accept the chat connection (we recommend about 120000).
 * @return a DccChat object that can be used to send and recieve lines of
 * text.  Returns <b>null</b> if the connection could not be made.
 * @see DccChat
 * @since PircBot 0.9.8
 */
public final DccChat dccSendChatRequest(String nick, int timeout) {
    DccChat chat = null;
    try {
        ServerSocket ss = null;

        int[] ports = getDccPorts();
        if (ports == null) {
            // Use any free port.
            ss = new ServerSocket(0);
        } else {
            for (int i = 0; i < ports.length; i++) {
                try {
                    ss = new ServerSocket(ports[i]);
                    // Found a port number we could use.
                    break;
                } catch (Exception e) {
                    // Do nothing; go round and try another port.
                }
            }
            if (ss == null) {
                // No ports could be used.
                throw new IOException("All ports returned by getDccPorts() are in use.");
            }
        }

        ss.setSoTimeout(timeout);
        int port = ss.getLocalPort();

        InetAddress inetAddress = getDccInetAddress();
        if (inetAddress == null) {
            inetAddress = getInetAddress();
        }
        byte[] ip = inetAddress.getAddress();
        long ipNum = ipToLong(ip);

        sendCTCPCommand(nick, "DCC CHAT chat " + ipNum + " " + port);

        // The client may now connect to us to chat.
        Socket socket = ss.accept();

        // Close the server socket now that we've finished with it.
        ss.close();

        chat = new DccChat(this, nick, socket);
    } catch (Exception e) {
        // Do nothing.
    }
    return chat;
}

From source file:catalina.core.StandardServer.java

/**
 * Wait until a proper shutdown command is received, then return.
 */// ww  w.  j ava  2 s. c om
public void await() {

    // Set up a server socket to wait on
    ServerSocket serverSocket = null;
    try {
        serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
    } catch (IOException e) {
        System.err.println("StandardServer.await: create[" + port + "]: " + e);
        e.printStackTrace();
        System.exit(1);
    }

    // Loop waiting for a connection and a valid command
    while (true) {

        // Wait for the next connection
        Socket socket = null;
        InputStream stream = null;
        try {
            socket = serverSocket.accept();
            socket.setSoTimeout(10 * 1000); // Ten seconds
            stream = socket.getInputStream();
        } catch (AccessControlException ace) {
            System.err.println("StandardServer.accept security exception: " + ace.getMessage());
            continue;
        } catch (IOException e) {
            System.err.println("StandardServer.await: accept: " + e);
            e.printStackTrace();
            System.exit(1);
        }

        // Read a set of characters from the socket
        StringBuffer command = new StringBuffer();
        int expected = 1024; // Cut off to avoid DoS attack
        while (expected < shutdown.length()) {
            if (random == null)
                random = new Random(System.currentTimeMillis());
            expected += (random.nextInt() % 1024);
        }
        while (expected > 0) {
            int ch = -1;
            try {
                ch = stream.read();
            } catch (IOException e) {
                System.err.println("StandardServer.await: read: " + e);
                e.printStackTrace();
                ch = -1;
            }
            if (ch < 32) // Control character or EOF terminates loop
                break;
            command.append((char) ch);
            expected--;
        }

        // Close the socket now that we are done with it
        try {
            socket.close();
        } catch (IOException e) {
            ;
        }

        // Match against our command string
        boolean match = command.toString().equals(shutdown);
        if (match) {
            break;
        } else
            System.err.println("StandardServer.await: Invalid command '" + command.toString() + "' received");

    }

    // Close the server socket and return
    try {
        serverSocket.close();
    } catch (IOException e) {
        ;
    }

}

From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java

/**
 * Establishes a data connection with the FTP server, returning
 * a Socket for the connection if successful.  If a restart
 * offset has been set with {@link #setRestartOffset(long)},
 * a REST command is issued to the server with the offset as
 * an argument before establishing the data connection.  Active
 * mode connections also cause a local PORT command to be issued.
 * <p>//from   w  w w.  j a  va 2s .c o m
 * @param command  The text representation of the FTP command to send.
 * @param arg The arguments to the FTP command.  If this parameter is
 *             set to null, then the command is sent with no argument.
 * @return A Socket corresponding to the established data connection.
 *         Null is returned if an FTP protocol error is reported at
 *         any point during the establishment and initialization of
 *         the connection.
 * @exception IOException  If an I/O error occurs while either sending a
 *      command to the server or receiving a reply from the server.
 * @since 3.1
 */
protected Socket _openDataConnection_(String command, String arg) throws IOException {
    if (__dataConnectionMode != ACTIVE_LOCAL_DATA_CONNECTION_MODE
            && __dataConnectionMode != PASSIVE_LOCAL_DATA_CONNECTION_MODE) {
        return null;
    }

    final boolean isInet6Address = getRemoteAddress() instanceof Inet6Address;

    Socket socket;

    if (__dataConnectionMode == ACTIVE_LOCAL_DATA_CONNECTION_MODE) {
        // if no activePortRange was set (correctly) -> getActivePort() = 0
        // -> new ServerSocket(0) -> bind to any free local port
        ServerSocket server = _serverSocketFactory_.createServerSocket(getActivePort(), 1, getHostAddress());

        try {
            // Try EPRT only if remote server is over IPv6, if not use PORT,
            // because EPRT has no advantage over PORT on IPv4.
            // It could even have the disadvantage,
            // that EPRT will make the data connection fail, because
            // today's intelligent NAT Firewalls are able to
            // substitute IP addresses in the PORT command,
            // but might not be able to recognize the EPRT command.
            if (isInet6Address) {
                if (!FTPReply.isPositiveCompletion(eprt(getReportHostAddress(), server.getLocalPort()))) {
                    return null;
                }
            } else {
                if (!FTPReply.isPositiveCompletion(port(getReportHostAddress(), server.getLocalPort()))) {
                    return null;
                }
            }

            if ((__restartOffset > 0) && !restart(__restartOffset)) {
                return null;
            }

            if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
                return null;
            }

            // For now, let's just use the data timeout value for waiting for
            // the data connection.  It may be desirable to let this be a
            // separately configurable value.  In any case, we really want
            // to allow preventing the accept from blocking indefinitely.
            if (__dataTimeout >= 0) {
                server.setSoTimeout(__dataTimeout);
            }
            socket = server.accept();

            // Ensure the timeout is set before any commands are issued on the new socket
            if (__dataTimeout >= 0) {
                socket.setSoTimeout(__dataTimeout);
            }
            if (__receiveDataSocketBufferSize > 0) {
                socket.setReceiveBufferSize(__receiveDataSocketBufferSize);
            }
            if (__sendDataSocketBufferSize > 0) {
                socket.setSendBufferSize(__sendDataSocketBufferSize);
            }
        } finally {
            server.close();
        }
    } else { // We must be in PASSIVE_LOCAL_DATA_CONNECTION_MODE

        // Try EPSV command first on IPv6 - and IPv4 if enabled.
        // When using IPv4 with NAT it has the advantage
        // to work with more rare configurations.
        // E.g. if FTP server has a static PASV address (external network)
        // and the client is coming from another internal network.
        // In that case the data connection after PASV command would fail,
        // while EPSV would make the client succeed by taking just the port.
        boolean attemptEPSV = isUseEPSVwithIPv4() || isInet6Address;
        if (attemptEPSV && epsv() == FTPReply.ENTERING_EPSV_MODE) {
            _parseExtendedPassiveModeReply(_replyLines.get(0));
        } else {
            if (isInet6Address) {
                return null; // Must use EPSV for IPV6
            }
            // If EPSV failed on IPV4, revert to PASV
            if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) {
                return null;
            }
            _parsePassiveModeReply(_replyLines.get(0));
        }

        socket = _socketFactory_.createSocket();
        if (__receiveDataSocketBufferSize > 0) {
            socket.setReceiveBufferSize(__receiveDataSocketBufferSize);
        }
        if (__sendDataSocketBufferSize > 0) {
            socket.setSendBufferSize(__sendDataSocketBufferSize);
        }
        if (__passiveLocalHost != null) {
            socket.bind(new InetSocketAddress(__passiveLocalHost, 0));
        }

        // For now, let's just use the data timeout value for waiting for
        // the data connection.  It may be desirable to let this be a
        // separately configurable value.  In any case, we really want
        // to allow preventing the accept from blocking indefinitely.
        if (__dataTimeout >= 0) {
            socket.setSoTimeout(__dataTimeout);
        }

        socket.connect(new InetSocketAddress(__passiveHost, __passivePort), connectTimeout);
        if ((__restartOffset > 0) && !restart(__restartOffset)) {
            socket.close();
            return null;
        }

        if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
            socket.close();
            return null;
        }
    }

    if (__remoteVerificationEnabled && !verifyRemote(socket)) {
        socket.close();

        throw new IOException("Host attempting data connection " + socket.getInetAddress().getHostAddress()
                + " is not same as server " + getRemoteAddress().getHostAddress());
    }

    return socket;
}

From source file:com.lfv.lanzius.server.LanziusServer.java

private void groupRemoteControlListener(final int port) {
    new Thread("RemoteControlThread") {
        public void run() {
            try {
                ServerSocket serverSocket = new ServerSocket(port);
                Socket socket = null;
                boolean listening = true;
                String inputLine;
                while (listening) {
                    socket = serverSocket.accept();
                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    inputLine = in.readLine();
                    log.debug("Remote control thread received: " + inputLine);
                    try {
                        String arglist[];
                        arglist = inputLine.split(" ");
                        String command = arglist[0];

                        if (command.equals("play")) {
                            String newtime;
                            String comment;

                            if (arglist.length >= 2)
                                newtime = arglist[1];
                            else
                                newtime = null;
                            menuChoiceGroupStart(1, false, newtime);
                            if (arglist.length >= 3)
                                comment = arglist[2];
                            else
                                comment = null;

                            if (comment != null) {
                                ServerLogger logger = loggerMap.get(1);
                                if (logger != null) {
                                    logger.print(comment);
                                }//from  w ww. j av  a 2 s .c o m
                            }
                        } else if (command.equals("stop")) {
                            menuChoiceGroupStop(1, false);
                        } else if (command.equals("pause")) {
                            String comment;
                            if (arglist.length >= 2)
                                comment = arglist[1];
                            else
                                comment = null;
                            if (comment != null) {
                                ServerLogger logger = loggerMap.get(1);
                                if (logger != null) {
                                    logger.print(comment);
                                }
                            }
                            menuChoiceGroupPause(1);
                        } else if (inputLine.startsWith("logpath")) {
                            String newlogPath;
                            newlogPath = inputLine.substring(inputLine.indexOf(' ') + 1);
                            ServerLogger logger = loggerMap.get(1);
                            if (logger != null) {
                                log.debug("ServerLogger.logpath=" + logger.getLogPath() + " new path="
                                        + newlogPath);
                                if (newlogPath != logger.getLogPath()) {
                                    log.debug("ServerLogger.logpath changed!!!!");

                                    loggerMap.remove(1);
                                    logger.print("GROUP STOP id[1]");
                                    logger.close();
                                    ServerLogger newlogger = new ServerLogger(1, newlogPath);
                                    loggerMap.put(1, newlogger);
                                    newlogger.print("GROUP START id[1]");
                                }
                            } else {
                                log.debug("No active logger for group 1");
                            }

                            if ((logPath != null) && (!(newlogPath.equals(logPath)))) {
                                log.debug("logPath changed, stopping Groups");
                            }
                            logPath = newlogPath;
                            log.debug("logPath set to " + logPath);
                        }
                    } catch (Exception e) {
                        log.debug("Remote control action failed");
                    }
                    socket.close();
                }
                serverSocket.close();
            } catch (IOException e) {
                log.error("Failed to start Remote Control listener thread!");
                log.error(e.getMessage());
            }
        }
    }.start();
    log.info("Group remote control listening on port " + port + ".");
}