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:LCModels.MessageTransmitter.java

@Override
public void run() {
    try {/* w w  w .  j  ava2 s . c  o  m*/
        // Socket connects to the ServerSocket, ServerSocket receives a Socket, what? haha//
        //send data as points
        //            Socket s = new Socket(hostname,targetPort);
        //            Socket z = new Socket(hostname, 48500, InetAddress.getByName("127.0.0.1"), targetPort);
        Socket client = new Socket(hostname, targetPort);
        /* Get server's OutputStream */
        OutputStream outToServer = client.getOutputStream();
        /* Get server's DataOutputStream to write/send message */
        DataOutputStream out = new DataOutputStream(outToServer);
        /* Write message to DataOutputStream */
        out.writeUTF(transmitJSON.toString());
        /* Get InputStream to get message from server */
        InputStream inFromServer = client.getInputStream();
        /* Get DataInputStream to read message of server */
        DataInputStream in = new DataInputStream(inFromServer);
        /* Print message received from server */
        System.out.println("Server says..." + in.readUTF());
        client.close();
    } catch (IOException ex) {
        Logger.getLogger(MessageTransmitter.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.hulaki.smtp.api.ApiClient.java

private String sendRequestToApiServer(ApiRequest request) {
    try {//from www.  j a v  a  2s  .c  o  m
        Socket clientSocket = new Socket(this.apiServerHostname, this.apiServerPort);
        DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());

        String requestString = request.toRequestString() + "\n";
        logger.trace(requestString);
        out.writeBytes(requestString);
        StringBuilder response = new StringBuilder();
        logger.trace(response.toString());

        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine).append("\n");
        }
        clientSocket.close();
        return response.toString();
    } catch (ConnectException e) {
        throw new ApiException("SMTP mock not available at " + apiServerHostname + ":" + apiServerPort);
    } catch (IOException e) {
        throw new ApiException(e);
    }
}

From source file:com.adito.tunnels.agent.RemoteTunnel.java

public void run() {
    // Process destination host and port for replacement variables
    VariableReplacement r = new VariableReplacement();
    r.setLaunchSession(launchSession);/*ww  w  .  j  a va2 s. c om*/
    String destHost = r.replace(tunnel.getDestination().getHost());

    ByteArrayWriter msg = new ByteArrayWriter();

    try {

        msg.writeInt(tunnel.getResourceId());
        msg.writeString(tunnel.getSourceInterface());
        msg.writeString(launchSession.getId());
        msg.writeString(tunnel.getSourceInterface());
        msg.writeInt(tunnel.getSourcePort());
        msg.writeString(destHost);
        msg.writeInt(tunnel.getDestination().getPort());

        Request request = new Request(TunnelingService.START_REMOTE_TUNNEL, msg.toByteArray());
        agent.sendRequest(request, false);

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    running = true;
    if (log.isInfoEnabled())
        log.info("Starting remote listener on " + tunnel.getSourcePort());
    try {
        while (running) {
            try {
                Socket s = listeningSocket.accept();
                if (log.isInfoEnabled())
                    log.info("Received new connection on " + tunnel.getSourcePort() + " from "
                            + s.getInetAddress());
                RemoteForwardingChannel channel = new RemoteForwardingChannel(this, s, tunnel, launchSession);
                try {
                    agent.openChannel(channel);
                } catch (ChannelOpenException e) {
                    log.error("Error opening channel. Remote tunnel remaining open but closing connection.", e);
                    try {
                        s.close();
                    } catch (IOException ioe) {
                    }
                }
            } catch (IOException e) {
                if (running) {
                    log.error("IO error waiting for connection, stopping remote tunnel.", e);
                }
            }
        }
    } finally {

        Request request = new Request(TunnelingService.STOP_REMOTE_TUNNEL, msg.toByteArray());
        try {
            agent.sendRequest(request, false);
        } catch (IOException e) {
        }

        Channel[] c = agent.getActiveChannels();
        if (c != null) {
            for (int i = 0; i < c.length; i++) {
                if (c[i] instanceof RemoteForwardingChannel) {
                    RemoteForwardingChannel rfc = (RemoteForwardingChannel) c[i];
                    if (rfc.getRemoteTunnel() == this && rfc.getConnection() != null) {
                        try {
                            rfc.close();
                        } catch (Throwable t) {
                            // TODO workaround for NPE
                            log.error("Failed to close channel.", t);
                        }
                    }
                }
            }
        }
        tunnelManager.removeRemoteTunnel(this);
        LaunchSessionFactory.getInstance().removeLaunchSession(launchSession);
        running = false;
    }
}

From source file:com.quigley.zabbixj.agent.active.ActiveThread.java

private void sendMetrics(int delay, List<String> keyList) throws Exception {
    if (log.isDebugEnabled()) {
        String message = "Sending metrics for delay '" + delay + "' with keys: ";
        for (int i = 0; i < keyList.size(); i++) {
            if (i > 0) {
                message += ", ";
            }//from  ww  w .j a v a2  s  .co m
            message += keyList.get(i);
        }
        log.debug(message);
    }

    long clock = System.currentTimeMillis() / 1000;

    JSONObject metrics = new JSONObject();
    metrics.put("request", "agent data");

    JSONArray data = new JSONArray();
    for (String keyName : keyList) {
        JSONObject key = new JSONObject();
        key.put("host", hostName);
        key.put("key", keyName);
        try {
            Object value = metricsContainer.getMetric(keyName);
            key.put("value", value.toString());

        } catch (Exception e) {
            key.put("value", "ZBX_NOTSUPPORTED");
        }
        key.put("clock", "" + clock);

        data.put(key);
    }
    metrics.put("data", data);
    metrics.put("clock", "" + clock);

    Socket socket = new Socket(serverAddress, serverPort);
    InputStream input = socket.getInputStream();
    OutputStream output = socket.getOutputStream();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    output.write(getRequest(metrics));
    output.flush();

    byte[] buffer = new byte[10240];
    int read = 0;
    while ((read = input.read(buffer, 0, 10240)) != -1) {
        baos.write(buffer, 0, read);
    }

    socket.close();

    JSONObject response = getResponse(baos.toByteArray());
    if (response.getString("response").equals("success")) {
        if (log.isDebugEnabled()) {
            log.debug("The server reported success '" + response.getString("info") + "'.");
        }
    } else {
        log.error("Failure!");
    }

    lastChecked.put(delay, clock);
}

From source file:com.salmonllc.ideTools.Tomcat50Engine.java

public void stopServer(String[] arguments, Tomcat50Bootstrap bootstrap) {

    if (_server == null) {
        // Create and execute our Digester
        Digester digester = createStopDigester();
        digester.setClassLoader(Thread.currentThread().getContextClassLoader());
        File file = configFile();
        try {//w  ww. j a va 2 s .co  m
            InputSource is = new InputSource("file://" + file.getAbsolutePath());
            FileInputStream fis = new FileInputStream(file);
            is.setByteStream(fis);
            digester.push(this);
            digester.parse(is);
            fis.close();
        } catch (Exception e) {
            System.out.println("Catalina.stop: " + e);
            e.printStackTrace(System.out);
            System.exit(1);
        }
    }

    // Stop the existing server
    try {
        String host = "127.0.0.1";
        int port = 8005;
        String shutdown = "SHUTDOWN";

        if (_shutdown != null) {
            port = _shutdown.getPort();
            shutdown = _shutdown.getShutdown();
        }

        Socket socket = new Socket(host, port);
        OutputStream stream = socket.getOutputStream();

        for (int i = 0; i < shutdown.length(); i++)
            stream.write(shutdown.charAt(i));
        stream.flush();
        stream.close();
        socket.close();
        Thread.sleep(500);
    } catch (Exception e) {
        //System.out.println("Catalina.stop: " + e);
        //e.printStackTrace(System.out);
        //System.exit(1);
    }

    bootstrap.notifyComplete();

}

From source file:de.ailis.oneinstance.OneInstance.java

/**
 * Registers this instance of the application. Returns true if the
 * application is allowed to run or false when the application must
 * exit immediately./* w ww  .  j av  a 2  s . c  o m*/
 * 
 * @param mainClass
 *            The main class of the application. Must not be null.
 *            This is used for determining the application ID and as
 *            the user node key for the preferences.
 * @param args
 *            The command line arguments. They are passed to an already
 *            running instance if found. Must not be null.
 * @return True if instance is allowed to start, false if not.
 */
public boolean register(Class<?> mainClass, final String[] args) {
    if (mainClass == null)
        throw new IllegalArgumentException("mainClass must be set");
    if (args == null)
        throw new IllegalArgumentException("args must be set");

    // Determine application ID from class name.
    String appId = mainClass.getName();

    try {
        // Acquire a lock
        File lockFile = getLockFile(appId);
        FileLock lock = lock(lockFile);

        try {
            // Get the port which is currently recorded as active.
            Integer port = getActivePort(mainClass);

            // If port is found then we have to validate it
            if (port != null) {
                // Try to connect to the first instance.
                Socket socket = openClientSocket(appId, port);

                // If connection is successful then run as a client
                // (non-first instance)
                if (socket != null) {
                    try {
                        // Run the client and return the result from the
                        // server
                        return runClient(socket, args);
                    } finally {
                        socket.close();
                    }
                }
            }

            // Run the server 
            runServer(mainClass);

            // Mark the lock file to be deleted when this instance exits.
            lockFile.deleteOnExit();

            // Allow this first instance to run.
            return true;
        } finally {
            release(lock);
        }
    } catch (IOException e) {
        // When something went wrong log the error as a warning and then
        // let instance start.
        LOG.warn(e.toString(), e);
        return true;
    }
}

From source file:com.qspin.qtaste.tcom.rlogin.RLogin.java

/**
 * Reboot the remote host by sending the reboot command and check that
 * the remote host is not accessible anymore.
 * @return true if success, false otherwise
 */// ww w . ja va2  s . co  m
public boolean reboot() {
    if (!sendCommand("reboot")) {
        return false;
    }

    // wait 1 second
    try {
        Thread.sleep(1000);
    } catch (InterruptedException ex) {
    }

    disconnect();

    // check that remote host is not accessible anymore
    // open a socket without any parameters. It hasn't been binded or connected
    Socket socket = new Socket();
    try {
        // bind to a local ephemeral port
        socket.bind(null);
        socket.connect(new InetSocketAddress(remoteHost, RLoginClient.DEFAULT_PORT), 1);
    } catch (SocketTimeoutException e) {
        logger.info("Rebooted host " + remoteHost + " successfully");
        return true;
    } catch (IOException e) {
        logger.error("Something went wrong while rebooting host:" + remoteHost);
        return false;
    } finally {
        try {
            socket.close();
        } catch (IOException ex) {
        }
        socket = null;
    }
    // Expected to get an exception as the remote host should not be reachable anymore
    logger.error("Host " + remoteHost
            + " did not reboot as expected! Please check that no other rlogin client is connected!");
    return false;
}

From source file:com.jredrain.startup.Bootstrap.java

/**
 *
 * @throws Exception//from w  ww  .j  av  a 2s.  co m
 */

private void shutdown() throws Exception {
    /**
     * connect to startup socket and send stop command
     */
    Socket socket = new Socket("localhost", RedrainProperties.getInt("redrain.shutdown"));
    OutputStream os = socket.getOutputStream();
    PrintWriter pw = new PrintWriter(os);
    InputStream is = socket.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    pw.write(shutdown);
    pw.flush();
    socket.shutdownOutput();
    String reply = null;
    while (!((reply = br.readLine()) == null)) {
        logger.info("[redrain]shutdown:{}" + reply);
    }
    br.close();
    is.close();
    pw.close();
    os.close();
    socket.close();
}

From source file:org.urbanstew.soundcloudapi.SoundCloudAPI.java

private void closeQuietly(Socket socket) {
    try {/*ww  w .  j  a  v a  2  s  .  c  om*/
        if (socket != null)
            socket.close();
    } catch (Exception e) {
        System.err.println("Exception during Socket close: " + e);
    }
}

From source file:net.lightbody.bmp.proxy.jetty.util.ThreadedServer.java

/**
 * Handle new connection. If access is required to the actual socket, override this method
 * instead of handleConnection(InputStream in,OutputStream out). The default implementation of
 * this just calls handleConnection(InputStream in,OutputStream out).
 *//*w  ww  .  j a  v  a2  s . c  om*/
protected void handleConnection(Socket connection) throws IOException {
    if (log.isDebugEnabled())
        log.debug("Handle " + connection);
    InputStream in = connection.getInputStream();
    OutputStream out = connection.getOutputStream();

    handleConnection(in, out);
    out.flush();

    in = null;
    out = null;
    connection.close();
}