Example usage for java.net Socket close

List of usage examples for java.net Socket close

Introduction

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

Prototype

public synchronized void close() throws IOException 

Source Link

Document

Closes this socket.

Usage

From source file:com.nohkumado.ipx800control.Ipx800Control.java

/**
 sendCmd//from   w ww.  j  a va 2 s.  co m
 @param cmd the command to send
 opens a TCP port and sends a m2m command to the ipx, stores the eventual result in 
  return in @see returnMsg
 */
protected boolean sendCmd(String cmd) {
    Socket socket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    //System.out.println("sendcmd for "+cmd);
    try {
        //System.out.println("opening "+server+":"+port);
        socket = new Socket(server, port);
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        //System.out.println("about to send out cmd");
        out.println(cmd);
        //System.out.println("waiting for return");
        returnMsg = in.readLine();
        //System.out.println("return from ipx:"+returnMsg);
        if (returnMsg.matches("=")) {
            String[] parts = returnMsg.split("=");
            //String part1 = parts[0]; // Getin
            returnMsg = parts[1]; // value
        }
        out.close();
        in.close();
        socket.close();
    } catch (UnknownHostException e) {
        System.err.println("Don't know about host " + server);
        return false;
    } catch (IOException e) {
        System.err.println("Couldn't get I/O for the connection");
        return false;
    }

    return true;
}

From source file:com.raddle.tools.ClipboardTransferMain.java

private Object doInSocket(SocketCallback callback) {
    Socket socket = null;
    try {/*w w  w .ja  va2s. co  m*/
        String address = serverAddrTxt.getText();
        String[] ipport = address.split(":");
        if (ipport.length != 2) {
            updateMessage("????");
            return null;
        }
        socket = new Socket();
        SocketAddress socketAddress = new InetSocketAddress(ipport[0], Integer.parseInt(ipport[1]));
        socket.connect(socketAddress, 2000);
        socket.setSoTimeout(10000);
        return callback.connected(socket);
    } catch (Exception e) {
        e.printStackTrace();
        updateMessage("?" + e.getMessage());
        return null;
    } finally {
        if (socket != null) {
            try {
                socket.getInputStream().close();
            } catch (IOException e) {
            }
            try {
                socket.getOutputStream().close();
            } catch (IOException e) {
            }
            try {
                socket.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:ca.uhn.hunit.example.MllpHl7v2MessageSwapper.java

@Override
public void run() {
    Socket socket = null;/*from   w  w w.j a v  a  2 s.c o m*/

    try {
        if (myPrintOutput) {
            System.out.println("Opening server socket on port " + 10201);
        }

        ServerSocket serverSocket = new ServerSocket(10201);

        socket = serverSocket.accept();

        InputStream inputStream = socket.getInputStream();
        inputStream = new BufferedInputStream(inputStream);

        MinLLPReader minLLPReader = new MinLLPReader(inputStream);

        Socket outSocket = null;

        if (myPrintOutput) {
            System.out.println("Accepting connection from " + socket.getInetAddress().getHostAddress());
        }

        for (int i = 0; i < myIterations; i++) {
            String messageText;

            do {
                messageText = minLLPReader.getMessage();
                Thread.sleep(250);
            } while (messageText == null);

            if (myPrintOutput) {
                System.out.println("Received message:\r\n" + messageText + "\r\n");
            }

            MSH inboundHeader = (MSH) myParser.parse(messageText).get("MSH");
            String controlId = inboundHeader.getMessageControlID().encode();
            if (StringUtils.isNotBlank(controlId) && myControlIdsToIgnore.indexOf(controlId) > -1) {
                Message replyAck = DefaultApplication.makeACK(inboundHeader);
                new MinLLPWriter(socket.getOutputStream()).writeMessage(myParser.encode(replyAck));
            } else {
                System.out.println("Ignoring message with control ID " + controlId);
            }

            for (Map.Entry<String, String> next : mySubstitutions.entrySet()) {
                messageText = messageText.replace(next.getKey(), next.getValue());
            }

            if ((outSocket != null) && myAlwaysCreateNewOutboundConnection) {
                outSocket.close();
                outSocket = null;
            }

            if (outSocket == null) {
                if (myPrintOutput) {
                    System.out.println("Opening outbound connection to port " + 10200);
                }

                outSocket = new Socket();
                outSocket.connect(new InetSocketAddress("localhost", 10200));
            }

            if (myPrintOutput) {
                System.out.println("Sending message from port " + outSocket.getLocalPort() + ":\r\n"
                        + messageText + "\r\n");
            }

            new MinLLPWriter(outSocket.getOutputStream()).writeMessage(messageText);
            new MinLLPReader(outSocket.getInputStream()).getMessage();
        }

        serverSocket.close();
        socket.close();

        myStopped = true;

    } catch (Exception e) {
        myStopped = true;
        e.printStackTrace();
    }
}

From source file:com.mirth.connect.server.util.ConnectorUtil.java

public static ConnectionTestResponse testConnection(String host, int port, int timeout, String localAddr,
        int localPort) throws Exception {
    Socket socket = null;
    InetSocketAddress address = null;
    InetSocketAddress localAddress = null;

    try {/*from  w  w w  .j  ava  2  s.com*/
        address = new InetSocketAddress(host, port);

        if (StringUtils.isBlank(address.getAddress().getHostAddress()) || (address.getPort() < 0)
                || (address.getPort() > 65534)) {
            throw new Exception();
        }
    } catch (Exception e) {
        return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, "Invalid host or port.");
    }

    if (localAddr != null) {
        try {
            localAddress = new InetSocketAddress(localAddr, localPort);

            if (StringUtils.isBlank(localAddress.getAddress().getHostAddress()) || (localAddress.getPort() < 0)
                    || (localAddress.getPort() > 65534)) {
                throw new Exception();
            }
        } catch (Exception e) {
            return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE,
                    "Invalid local host or port.");
        }
    }

    try {
        socket = new Socket();

        if (localAddress != null) {
            try {
                socket.bind(localAddress);
            } catch (Exception e) {
                return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE,
                        "Could not bind to local address: " + localAddress.getAddress().getHostAddress() + ":"
                                + localAddress.getPort());
            }
        }

        socket.connect(address, timeout);
        String connectionInfo = socket.getLocalAddress().getHostAddress() + ":" + socket.getLocalPort() + " -> "
                + address.getAddress().getHostAddress() + ":" + address.getPort();
        return new ConnectionTestResponse(ConnectionTestResponse.Type.SUCCESS,
                "Successfully connected to host: " + connectionInfo, connectionInfo);
    } catch (SocketTimeoutException ste) {
        return new ConnectionTestResponse(ConnectionTestResponse.Type.TIME_OUT, "Timed out connecting to host: "
                + address.getAddress().getHostAddress() + ":" + address.getPort());
    } catch (Exception e) {
        return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, "Could not connect to host: "
                + address.getAddress().getHostAddress() + ":" + address.getPort());
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
}

From source file:it.jnrpe.client.JNRPEClient.java

/**
 * Inovoke a command installed in JNRPE.
 * /*w  w w.j av a  2 s .  c o m*/
 * @param sCommandName
 *            The name of the command to be invoked
 * @param arguments
 *            The arguments to pass to the command (will substitute the
 *            $ARGSx$ parameters)
 * @return The value returned by the server
 * @throws JNRPEClientException
 *             Thrown on any communication error.
 */
public final ReturnValue sendCommand(final String sCommandName, final String... arguments)
        throws JNRPEClientException {
    SocketFactory socketFactory;

    Socket s = null;
    try {
        if (!useSSL) {
            socketFactory = SocketFactory.getDefault();
        } else {
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");

            sslContext.init(null, new TrustManager[] { getTrustManager() }, new SecureRandom());

            socketFactory = sslContext.getSocketFactory();
        }

        s = socketFactory.createSocket();
        if (weakCipherSuitesEnabled) {
            SSLSocket ssl = (SSLSocket) s;
            ssl.setEnabledCipherSuites(ssl.getSupportedCipherSuites());
        }

        s.setSoTimeout((int) TimeUnit.SECOND.convert(communicationTimeout));
        s.connect(new InetSocketAddress(serverIPorURL, serverPort));
        JNRPERequest req = new JNRPERequest(sCommandName, arguments);

        s.getOutputStream().write(req.toByteArray());

        InputStream in = s.getInputStream();
        JNRPEResponse res = new JNRPEResponse(in);

        return new ReturnValue(Status.fromIntValue(res.getResultCode()), res.getMessage());
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        throw new JNRPEClientException(e);
    } finally {
        if (s != null) {
            try {
                s.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    }
}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an telnet connection to a target host and port number. Silently
 * succeeds if no issues are encountered, if so, exceptions are logged and
 * re-thrown back to the requestor.//from ww  w  . ja v a2  s .co  m
 *
 * If an exception is thrown during the <code>socket.close()</code> operation,
 * it is logged but NOT re-thrown. It's not re-thrown because it does not indicate
 * a connection failure (indeed, it means the connection succeeded) but it is
 * logged because continued failures to close the socket could result in target
 * system instability.
 * 
 * @param hostName - The target host to make the connection to
 * @param portNumber - The port number to attempt the connection on
 * @param timeout - The timeout for the connection
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized void executeTelnetRequest(final String hostName, final int portNumber,
        final int timeout) throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeTelnetRequest(final String hostName, final int portNumber, final int timeout) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug(hostName);
        DEBUGGER.debug("portNumber: {}", portNumber);
        DEBUGGER.debug("timeout: {}", timeout);
    }

    Socket socket = null;

    try {
        synchronized (new Object()) {
            if (InetAddress.getByName(hostName) == null) {
                throw new UnknownHostException("No host was found in DNS for the given name: " + hostName);
            }

            InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber);

            socket = new Socket();
            socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout));
            socket.setSoLinger(false, 0);
            socket.setKeepAlive(false);
            socket.connect(socketAddress, (int) TimeUnit.SECONDS.toMillis(timeout));

            if (!(socket.isConnected())) {
                throw new ConnectException("Failed to connect to host " + hostName + " on port " + portNumber);
            }

            PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);

            pWriter.println(NetworkUtils.TERMINATE_TELNET + NetworkUtils.CRLF);

            pWriter.flush();
            pWriter.close();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } finally {
        try {
            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            // log it - this could cause problems later on
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }
}

From source file:android.core.SSLSocketTest.java

/**
 * Regression test for problem where close() resulted in a hand if
 * a different thread was sitting in a blocking read or write.
 *//* ww  w.  j a  v  a  2  s  .com*/
public void testMultithreadedClose() throws Exception {
    InetSocketAddress address = new InetSocketAddress("www.fortify.net", 443);
    final Socket socket = clientFactory.createSocket();
    socket.connect(address);

    Thread reader = new Thread() {
        @Override
        public void run() {
            try {
                byte[] buffer = new byte[512];
                InputStream stream = socket.getInputStream();
                socket.getInputStream().read(buffer);
            } catch (Exception ex) {
                android.util.Log.d("SSLSocketTest", "testMultithreadedClose() reader got " + ex.toString());
            }
        }
    };

    Thread closer = new Thread() {
        @Override
        public void run() {
            try {
                Thread.sleep(5000);
                socket.close();
            } catch (Exception ex) {
                android.util.Log.d("SSLSocketTest", "testMultithreadedClose() closer got " + ex.toString());
            }
        }
    };

    android.util.Log.d("SSLSocketTest", "testMultithreadedClose() starting reader...");
    reader.start();
    android.util.Log.d("SSLSocketTest", "testMultithreadedClose() starting closer...");
    closer.start();

    long t1 = System.currentTimeMillis();
    android.util.Log.d("SSLSocketTest", "testMultithreadedClose() joining reader...");
    reader.join(30000);
    android.util.Log.d("SSLSocketTest", "testMultithreadedClose() joining closer...");
    closer.join(30000);
    long t2 = System.currentTimeMillis();

    assertTrue("Concurrent close() hangs", t2 - t1 < 30000);
}

From source file:gov.hhs.fha.nhinc.lift.proxy.client.ClientConnector.java

@Override
public void run() {
    /*/*w  w w  .  j a v  a 2 s. c  o m*/
     * Accept a connection and tunnel messages through the proxy system.
     */
    Socket socket = null;
    try {
        Thread toProxyThread;
        Thread fromProxyThread;

        socket = server.accept();
        log.debug("Server accepting to socket " + socket.getInetAddress());
        Connector toProxy = new Connector(socket.getInputStream(), proxyConnection.getOutStream(), bufferSize);
        Connector fromProxy = new Connector(proxyConnection.getInStream(), socket.getOutputStream(),
                bufferSize);

        toProxyThread = new Thread(toProxy, "Client To Proxy");
        fromProxyThread = new Thread(fromProxy, "Client From Proxy");

        toProxyThread.start();
        fromProxyThread.start();

        log.debug("Waiting to finish " + toProxyThread.getName());
        toProxyThread.join();

    } catch (IOException e) {
        String errorMsg = "Problem in creating client to proxy connectors: " + e.getMessage();
        log.error(errorMsg);
        controller.reportFailure(proxyConnection.getToken().getRequest(), errorMsg);
    } catch (InterruptedException e) {
        String errorMsg = "Client to proxy communication thread interrupted: " + e.getMessage();
        log.error(errorMsg);
        controller.reportFailure(proxyConnection.getToken().getRequest(), errorMsg);
    } finally {
        if (socket != null) {
            try {
                log.debug("Closing socket " + socket.getInetAddress() + ": " + socket.getPort());
                // Also closes associated streams
                socket.close();
            } catch (IOException ex) {
                log.warn("Unable to close client to proxy socket: " + ex.getMessage());
            }
        }
        if (proxyConnection != null) {
            try {
                log.debug("Closing proxy connection " + proxyConnection.getSocket().getInetAddress() + ": "
                        + proxyConnection.getSocket().getPort());
                proxyConnection.close();
            } catch (IOException ex) {
                log.warn("Unable to close proxy connection: " + ex.getMessage());
            }
        }
        if (server != null) {
            try {
                log.debug("Closing client connection server" + server.getInetAddress() + ": "
                        + server.getLocalPort());
                server.close();
            } catch (IOException ex) {
                log.warn("Unable to close proxy connection: " + ex.getMessage());
            }
        }
    }
}

From source file:com.tomagoyaky.jdwp.IOUtils.java

/**
 * Closes a <code>Socket</code> unconditionally.
 * <p/>/*from  w ww.jav  a 2s  . c  o m*/
 * Equivalent to {@link Socket#close()}, except any exceptions will be ignored.
 * This is typically used in finally blocks.
 * <p/>
 * Example code:
 * <pre>
 *   Socket socket = null;
 *   try {
 *       socket = new Socket("http://www.foo.com/", 80);
 *       // process socket
 *       socket.close();
 *   } catch (Exception e) {
 *       // error handling
 *   } finally {
 *       IOUtils.closeQuietly(socket);
 *   }
 * </pre>
 *
 * @param sock the Socket to close, may be null or already closed
 * @since 2.0
 */
public static void closeQuietly(final Socket sock) {
    if (sock != null) {
        try {
            sock.close();
        } catch (final IOException ioe) {
            // ignored
        }
    }
}

From source file:com.adito.server.DefaultAditoServerFactory.java

private void setupMode() throws Exception {
    // Ensure that https redirect is not turned on in jetty
    System.setProperty("jetty.force.HTTPSRedirect", "false");

    getBootProgressMonitor().updateMessage("Creating server");
    getBootProgressMonitor().updateProgress(8);

    actualPort = defaultPort == -1 ? 28080 : defaultPort;
    serverLock.start(actualPort);//w  w  w .j a v  a 2 s  . c o m

    server = createServer();

    SocketListener socketListener = new SocketListener();
    socketListener.setPort(actualPort);
    socketListener.setMinThreads(10);
    socketListener.setMaxThreads(200);
    socketListener.setMaxIdleTimeMs(0);
    socketListener.setLowResourcePersistTimeMs(2000);
    socketListener.setAcceptQueueSize(0);
    socketListener.setPoolName("P1");
    server.addListener(socketListener);

    getBootProgressMonitor().updateMessage("Creating web application");
    getBootProgressMonitor().updateProgress(9);

    webappContext = new CustomWebApplicationContext(useDevConfig, bootLoader);
    webappContext.setRedirectNullPath(false);
    addLifecycleListener(webappContext);
    server.addContext(webappContext);

    // Configure the server
    server.setRequestsPerGC(2000);

    String realHostname = hostname == null ? InetAddress.getLocalHost().getHostName() : hostname;

    /*
     * If the 'Active DNS' feature is enabled, the DNS server may return the
     * wild-card name. This will probably fail. As a work-around, if the
     * hostname looks like a wildcard, then it is simply changed to
     * 'localhost'.
     */
    if (realHostname.startsWith("*.")) {
        realHostname = "localhost";
    }

    //
    final String fRealHostname = realHostname;
    final int realPort = defaultPort == -1 ? 28080 : defaultPort;

    // Inform the wrapper the startup process is going ok
    if (useWrapper) {
        WrapperManager.signalStarting(60000);
    }

    mainThread = new Thread(threadGroup, "WebServer") {
        @Override
        public void run() {
            // Start the server
            try {
                server.start();

                if (!useWrapper && !"true".equals(SystemProperties.get("adito.noBrowserLaunch"))) {
                    try {
                        BrowserLauncher.openURL("http://" + fRealHostname + ":" + realPort);
                        System.out.println("A browser has been opened and pointed to http://" + fRealHostname
                                + ":" + realPort + ". ");
                    } catch (IOException ex) {
                        System.out.println(
                                "Point your browser to http://" + fRealHostname + ":" + realPort + ". ");
                    }
                } else {
                    System.out.println("Point your browser to http://" + fRealHostname + ":" + realPort + ". ");
                }
                System.out.println(
                        "\nPress CTRL+C or use the 'Shutdown' option from the web interface to leave the installation wizard.");
                getBootProgressMonitor().updateMessage("Server is now running");
                getBootProgressMonitor().updateProgress(100);
                Thread.sleep(2000);
            } catch (Exception e) {
                LOG.error("Failed to start Jetty. " + e.getMessage(), e);
                if (useWrapper) {
                    WrapperManager.stop(1);
                } else {
                    System.exit(1);
                }
            } finally {
                getBootProgressMonitor().dispose();
            }
        }
    };

    System.out.print("Starting installation wizard");
    mainThread.start();

    /*
     * Wait for up to 5 minutes for the server to become available we need
     * to wait this long because precompilation can take a while!
     */
    int waitFor = 60 * 5;

    boolean running = false;

    if (!"true".equals(SystemProperties.get("adito.disableStartupCheck", "false"))) {
        int i = 0;
        for (; i < waitFor && !running; i++) {
            try {
                System.out.print(".");
                Socket s = new Socket(realHostname, realPort);
                s.close();
                running = true;
            } catch (IOException ex) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex2) {
                }
            }
        }
        System.out.println();
    } else {
        running = true;
    }
    if (!running) {
        System.out.println("Failed to start installation wizard. Check the logs for more detail.");
        if (useWrapper) {
            WrapperManager.stop(1);
        } else {
            System.exit(1);
        }
    }
}