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:org.prx.prp.StreamProxy.java

private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException {
    if (request == null) {
        return;/*  www  .ja v  a 2 s. c o  m*/
    }
    Log.d(getClass().getName(), "processing");
    String url = request.getRequestLine().getUri();
    HttpResponse realResponse = download(url);
    if (realResponse == null) {
        return;
    }

    Log.d(getClass().getName(), "downloading...");

    InputStream data = realResponse.getEntity().getContent();
    StatusLine line = realResponse.getStatusLine();
    HttpResponse response = new BasicHttpResponse(line);
    response.setHeaders(realResponse.getAllHeaders());

    Log.d(getClass().getName(), "reading headers");
    StringBuilder httpString = new StringBuilder();
    httpString.append(response.getStatusLine().toString());

    httpString.append("\n");
    for (Header h : response.getAllHeaders()) {
        httpString.append(h.getName()).append(": ").append(h.getValue()).append("\n");
    }
    httpString.append("\n");
    Log.d(getClass().getName(), "headers done");
    //Log.d("PRPAND","Response "+httpString);
    try {
        byte[] buffer = httpString.toString().getBytes();
        int readBytes = -1;
        Log.d(getClass().getName(), "writing to client");
        client.getOutputStream().write(buffer, 0, buffer.length);

        // Start streaming content.
        byte[] buff = new byte[1024 * 50];
        while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) {
            client.getOutputStream().write(buff, 0, readBytes);
        }
    } catch (Exception e) {
        Log.e("", e.getMessage(), e);
    } finally {
        if (data != null) {
            data.close();
        }
        client.close();

    }
}

From source file:com.twinsoft.convertigo.eclipse.learnproxy.http.HttpProxyWorker.java

public void run() {
    long duration, starttime = System.currentTimeMillis();
    Socket destinationSocket = null;
    try {//from   w w w  .  j  a v a2 s. c  om
        BufferedOutputStream proxyClientStream = new BufferedOutputStream(proxySocket.getOutputStream());

        // read client request
        HttpRequest request = handleRequest(proxySocket);
        this.request = request;

        // send request to server
        //logger.debug("connecting to: " + request.getHost() + ":" + request.getPort());
        if (!((System.getProperty("http.proxyHost") == null)
                || System.getProperty("http.proxyHost").trim().equals(""))) {
            String proxyHost = System.getProperty("http.proxyHost");
            String proxyPortStr = System.getProperty("http.proxyPort");
            if (proxyPortStr == null || proxyPortStr.trim().equals("")) {
                proxyPortStr = "80";
            }
            int proxyPort = Integer.parseInt(proxyPortStr);
            //logger.debug("connecting via proxy: " + proxyHost + ":" + proxyPort);
            destinationSocket = new Socket(proxyHost, proxyPort);
        } else {
            destinationSocket = new Socket(request.getHost(), request.getPort());
        }
        OutputStream destinationOutputStream = destinationSocket.getOutputStream();
        destinationOutputStream.write(request.getRequest(), 0, request.getRequest().length);
        destinationOutputStream.flush();
        //logger.debug("request sent");

        // read response from server
        HttpResponse response = handleResponse(destinationSocket, proxyClientStream);
        this.response = response;
        destinationSocket.close();
        destinationSocket = null;

        // send response to client
        proxyClientStream.flush();
        proxySocket.close();
        proxySocket = null;
        duration = System.currentTimeMillis() - starttime;
        //logger.debug("duration: " + duration);
        String path = "http://" + request.getHost()
                + ((request.getPort() == 80) ? "" : (":" + request.getPort())) + request.getPath();
        proxy.setWorkerResult(request.getMethod(), String.valueOf(response.getStatusCode()), path, starttime,
                request.getRequest(), this.response.getResponse(), duration);
    } catch (Exception e) {
        //logger.error("Error occurred: " + e.toString());
        duration = System.currentTimeMillis() - starttime;
        if (request != null) {
            String path = "http://" + request.getHost()
                    + ((request.getPort() == 80) ? "" : (":" + request.getPort())) + request.getPath();
            if (response != null && response.getResponse() != null) {
                proxy.setWorkerResult(request.getMethod(), String.valueOf(response.getStatusCode()), path,
                        starttime, request.getRequest(), response.getResponse(), duration);
            } else {
                proxy.setWorkerResult(request.getMethod(), "XXX", path, starttime, request.getRequest(),
                        ("no response available - " + e.toString()).getBytes(), duration);
            }
        } else {
            proxy.setWorkerResult("---", "---", "---", starttime, e.toString().getBytes(),
                    "no response available".getBytes(), duration);
        }
        try {
            if (proxySocket != null) {
                closeSocket(proxySocket);
            }
        } finally {
            if (destinationSocket != null) {
                closeSocket(destinationSocket);
            }
        }
    }
}

From source file:com.mobiperf.measurements.RRCTask.java

/**
 * Time how long it takes to do a TCP 3-way handshake, starting from the induced RRC state.
 * //www .  ja  va  2 s.c  o m
 * <ol>
 * <li> Send a packet to initiate the RRC state desired. </li>
 * <li> Open a TCP connection to the echo host server. </li>
 * <li> Time how long it took to look it up. </li>
 * <li> Count the total packets sent, globally on  the phone. If more packets were sent than 
 * expected, abort and try again. </li>
 * <li> Otherwise, save the data for that test and move to the next inter-packet interval.
 * </ol>
 * 
 * @param times List of inter-packet intervals, in half-second increments, at which to run the 
 * test
 * @param desc Stores parameters for the RRC inference tests in general
 */
public void runTCPHandshakeTest(final Integer[] times, RRCDesc desc) {
    Logger.d("Active inference TCP test: about to begin");
    if (times.length != desc.tcpTest.length) {
        desc.tcpTest = new int[times.length];
    }
    long startTime = 0;
    long endTime = 0;
    long dataConsumedThisTask = 0;

    try {
        // For each inter-packet interval...
        for (int i = 0; i < times.length; i++) {
            // On a failure, try again until a threshhold is reached.
            for (int j = 0; j < desc.GIVEUP_THRESHHOLD; j++) {
                checkIfWifi();
                if (stop) {
                    return;
                }

                PacketMonitor packetMonitor = new PacketMonitor();

                // Induce DCH then wait for specified time
                InetAddress serverAddr;
                serverAddr = InetAddress.getByName(desc.echoHost);
                sendPacket(serverAddr, desc.MAX, desc);
                waitTime(times[i] * 500, true);

                // begin test. We test the time to do a 3-way handshake only.
                startTime = System.currentTimeMillis();

                serverAddr = InetAddress.getByName(desc.target);
                // three-way handshake done when socket created
                Socket socket = new Socket(serverAddr, 80);
                endTime = System.currentTimeMillis();

                // Not exact, but also a smallish task...
                dataConsumedThisTask += DnsLookupTask.AVG_DATA_USAGE_BYTE;

                // Check how many packets were sent again. If the expected number
                // of packets were sent, we can finish and go to the next task.
                // Otherwise, we have to try again.
                if (!packetMonitor.isTrafficInterfering(5, 4)) {
                    socket.close();
                    break;
                }
                startTime = 0;
                endTime = 0;
                socket.close();
            }
            long rtt = endTime - startTime;
            try {
                desc.setTcp(i, (int) rtt);
            } catch (MeasurementError e) {
                e.printStackTrace();
            }
            Logger.d("Time for TCP" + rtt);
        }
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    incrementData(dataConsumedThisTask);
}

From source file:edu.vt.middleware.gator.server.SocketServer.java

/** {@inheritDoc}. */
public void run() {
    while (serverSocket != null && serverSocket.isBound()) {
        logger.info("Waiting to accept a new client.");

        Socket socket = null;
        InetAddress inetAddress = null;
        try {/* w  w  w  . j  a v  a  2  s .  com*/
            socket = serverSocket.accept();
            inetAddress = socket.getInetAddress();

            // Validate newly-connected client
            if (eventHandlerMap.keySet().size() >= maxClients) {
                throw new UnauthorizedClientException(inetAddress, "Maximum number of clients exceeded.");
            }
            final ProjectConfig project = getProject(inetAddress);
            if (project == null) {
                throw new UnauthorizedClientException(inetAddress, "Client not registered with any projects.");
            }

            // Explicitly enable TCP keep alives to try to help reclaim resources
            // from dead clients
            socket.setKeepAlive(true);

            logger.info("Accepted connection from client " + inetAddress);
            logger.info("Configuring logger repository for " + inetAddress);
            final LoggingEngine engine = getLoggingEngine(project);
            if (engine != null) {
                engine.register(inetAddress, project);
                logger.info("Successfully configured " + engine);
                final LoggingEventHandler handler = new LoggingEventHandler(socket, engine, eventExecutor);
                handler.getSocketCloseListeners().add(this);
                eventHandlerMap.put(inetAddress, handler);
                handlerExecutor.execute(handler);
            } else {
                logger.warn(String.format("Logging engine not found for %s.  Closing socket for %s.", project,
                        inetAddress));
                socket.close();
            }
        } catch (UnauthorizedClientException e) {
            logger.warn(String.format("Unauthorized client %s rejected for reason: " + e.getMessage(),
                    e.getClient()));
            if (socket != null && !socket.isClosed()) {
                logger.info("Closing socket for rejected host.");
                try {
                    socket.close();
                } catch (IOException ioex) {
                    logger.error("Error closing client socket.", ioex);
                }
            }
        } catch (SocketException e) {
            // Check whether this is caused by a stop() invocation:
            // calling stop() closes server socket, which throws SocketException
            // from blocking accept() call
            if (serverSocket == null) {
                logger.info("Ignoring SocketException caused by stop() invocation.");
            } else {
                logger.error(e);
            }
        } catch (Exception e) {
            logger.error(e);
        }
    }
}

From source file:org.testeditor.fixture.swt.SwtBotFixture.java

/**
 * Returns true if the application is launched.
 * /*from  www .j av  a2 s. c  o m*/
 * @return true, if the server is ready.
 */
private boolean isLaunched() {
    try {
        Socket client = getSocket();
        LOGGER.info("Is server ready for " + testName + "?");
        PrintStream os = new PrintStream(client.getOutputStream(), false, CHARSET_UTF_8);
        os.println("isLaunched");
        os.flush();
        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), CHARSET_UTF_8));
        String s = in.readLine();
        LOGGER.info(s);
        client.close();
        return Boolean.valueOf(s);
    } catch (UnknownHostException e) {
        LOGGER.error("isLaunched UnknownHostException: ", e);
    } catch (ConnectException e) {
        LOGGER.trace("Server not available.");
    } catch (IOException e) {
        LOGGER.error("isLaunched IOException: ", e);
    }
    return false;
}

From source file:org.psit.transwatcher.TransWatcher.java

@Override
public void run() {

    try {/*from  w  ww  . j  av a  2  s . c  om*/
        while (true) {

            String cardIP = connectAndGetCardIP();
            if (cardIP != null) {
                notifyMessage("Found SD card, IP: " + cardIP);

                // handshake successful, open permanent TCP connection
                // to listen to new images
                Socket newImageListenerSocket = null;
                try {
                    newImageListenerSocket = new Socket(cardIP, 5566);
                    newImageListenerSocket.setKeepAlive(true);
                    InputStream is = newImageListenerSocket.getInputStream();
                    byte[] c = new byte[1];
                    byte[] singleMessage = new byte[255];
                    int msgPointer = 0;

                    startConnectionKeepAliveWatchDog(newImageListenerSocket);

                    startImageDownloaderQueue(cardIP);

                    setState(State.LISTENING);

                    // loop to wait for new images
                    while (newImageListenerSocket.isConnected()) {
                        if (is.read(c) == 1) {
                            if (0x3E == c[0]) { // >
                                // start of filename
                                msgPointer = 0;
                            } else if (0x00 == c[0]) {
                                // end of filename
                                String msg = new String(Arrays.copyOfRange(singleMessage, 0, msgPointer));
                                notifyMessage("Image shot: " + msg);

                                // add to download queue
                                queue.add(msg);
                            } else {
                                // single byte. add to buffer
                                singleMessage[msgPointer++] = c[0];
                            }
                        }
                    }
                    setState(State.SEARCHING_CARD);
                } catch (IOException e) {
                    notifyMessage("Error during image notification connection!");
                } finally {
                    try {
                        newImageListenerSocket.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                notifyMessage("No card found, retrying.");
            }
            Thread.sleep(2000);
        }
    } catch (InterruptedException e) {
        stopImageDownLoaderQueue();
        notifyMessage("Connection abandoned.");
    }

}

From source file:org.jmxtrans.embedded.samples.graphite.GraphiteDataInjector.java

public void exportMetrics(TimeSeries timeSeries) throws IOException {
    System.out.println("Export '" + timeSeries.getKey() + "' to " + graphiteHost + " with prefix '"
            + graphiteMetricPrefix + "'");
    Socket socket = new Socket(graphiteHost, graphitePort);
    OutputStream outputStream = socket.getOutputStream();

    if (generateDataPointsFile) {
        JFreeChart chart = ChartFactory.createXYLineChart("Purchase", "date", "Amount",
                new TimeSeriesCollection(timeSeries), PlotOrientation.VERTICAL, true, true, false);
        // chart.getXYPlot().setRenderer(new XYSplineRenderer(60));

        File file = new File("/tmp/" + timeSeries.getKey() + ".png");
        ChartUtilities.saveChartAsPNG(file, chart, 1200, 800);
        System.out.println("Exported " + file.getAbsolutePath());

        String pickleFileName = "/tmp/" + timeSeries.getKey().toString() + ".pickle";
        System.out.println("Generate " + pickleFileName);
        outputStream = new TeeOutputStream(outputStream, new FileOutputStream(pickleFileName));
    }/*from   w  ww  .  ja  v a  2 s  .c om*/

    PyList list = new PyList();

    for (int i = 0; i < timeSeries.getItemCount(); i++) {
        if (debug)
            System.out.println(new DateTime(timeSeries.getDataItem(i).getPeriod().getStart()) + "\t"
                    + timeSeries.getDataItem(i).getValue().intValue());
        String metricName = graphiteMetricPrefix + timeSeries.getKey().toString();
        int time = (int) TimeUnit.SECONDS.convert(timeSeries.getDataItem(i).getPeriod().getStart().getTime(),
                TimeUnit.MILLISECONDS);
        int value = timeSeries.getDataItem(i).getValue().intValue();

        list.add(new PyTuple(new PyString(metricName), new PyTuple(new PyInteger(time), new PyInteger(value))));

        if (list.size() >= batchSize) {
            System.out.print("-");
            rateLimiter.acquire(list.size());
            sendDataPoints(outputStream, list);
        }
    }

    // send last data points
    if (!list.isEmpty()) {
        rateLimiter.acquire(list.size());
        sendDataPoints(outputStream, list);
    }

    Flushables.flushQuietly(outputStream);
    Closeables.close(outputStream, true);
    try {
        socket.close();
    } catch (Exception e) {
        // swallow exception
        e.printStackTrace();
    }

    System.out.println();
    System.out.println("Exported " + timeSeries.getKey() + ": " + timeSeries.getItemCount() + " items");
}

From source file:expect4j.ExpectUtils.java

/**
 * Creates an HTTP client connection to a specified HTTP server and
 * returns the entire response.  This function simulates <code>curl
 * http://remotehost/url</code>./* w  w w . j a va2  s  . co  m*/
 *
 * @param remotehost the DNS or IP address of the HTTP server
 * @param url the path/file of the resource to look up on the HTTP
 *        server
 * @return the response from the HTTP server
 * @throws Exception upon a variety of error conditions
 */
public static String Http(String remotehost, String url) throws Exception {
    Socket s = null;
    s = new Socket(remotehost, 80);
    logger.debug("Connected to " + s.getInetAddress().toString());

    if (false) {
        // for serious connection-oriented debugging only
        PrintWriter out = new PrintWriter(s.getOutputStream(), false);
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        System.out.println("Sending request");
        out.print("GET " + url + " HTTP/1.1\r\n");
        out.print("Host: " + remotehost + "\r\n");
        out.print("Connection: close\r\n");
        out.print("User-Agent: Expect4j\r\n");
        out.print("\r\n");
        out.flush();
        System.out.println("Request sent");

        System.out.println("Receiving response");
        String line;
        while ((line = in.readLine()) != null)
            System.out.println(line);
        System.out.println("Received response");
        if (line == null)
            System.exit(0);
    }

    Expect4j expect = new Expect4j(s);

    logger.debug("Sending HTTP request for " + url);
    expect.send("GET " + url + " HTTP/1.1\r\n");
    expect.send("Host: " + remotehost + "\r\n");
    expect.send("Connection: close\r\n");
    expect.send("User-Agent: Expect4j\r\n");
    expect.send("\r\n");

    logger.debug("Waiting for HTTP response");
    String remaining = null;
    expect.expect(new Match[] { new RegExpMatch("HTTP/1.[01] \\d{3} (.*)\n?\r", new Closure() {
        public void run(ExpectState state) {
            logger.trace("Detected HTTP Response Header");

            // save http code
            String match = state.getMatch();
            String parts[] = match.split(" ");

            state.addVar("httpCode", parts[1]);
            state.exp_continue();
        }
    }), new RegExpMatch("Content-Type: (.*\\/.*)\r\n", new Closure() {
        public void run(ExpectState state) {
            logger.trace("Detected Content-Type header");
            state.addVar("contentType", state.getMatch());
            state.exp_continue();
        }
    }), new EofMatch(new Closure() { // should cause entire page to be collected
        public void run(ExpectState state) {
            logger.trace("Found EOF, done receiving HTTP response");
        }
    }), // Will cause buffer to be filled up till end
            new TimeoutMatch(10000, new Closure() {
                public void run(ExpectState state) {
                    logger.trace("Timeout waiting for HTTP response");
                }
            }) });

    remaining = expect.getLastState().getBuffer(); // from EOF matching

    String httpCode = (String) expect.getLastState().getVar("httpCode");

    String contentType = (String) expect.getLastState().getVar("contentType");

    s.close();

    return remaining;
}

From source file:edu.vt.middleware.gator.log4j.SocketServer.java

/** {@inheritDoc}. */
public void run() {
    while (serverSocket != null && serverSocket.isBound()) {
        logger.info("Waiting to accept a new client.");

        Socket socket = null;
        InetAddress inetAddress = null;
        try {// w ww  .  j  a va 2s.  c om
            socket = serverSocket.accept();
            inetAddress = socket.getInetAddress();

            // Validate newly-connected client
            if (eventHandlerMap.keySet().size() >= maxClients) {
                throw new UnauthorizedClientException(inetAddress, "Maximum number of clients exceeded.");
            }
            final ProjectConfig project = getProject(inetAddress);
            if (project == null) {
                throw new UnauthorizedClientException(inetAddress, "Client not registered with any projects.");
            }

            // Explicitly enable TCP keep alives to try to help reclaim resources
            // from dead clients
            socket.setKeepAlive(true);

            logger.info("Accepted connection from client " + inetAddress);
            logger.info("Configuring logger repository for " + inetAddress);
            final LoggerRepository repo = getLoggerRepository(project);
            configurator.configure(project, repo);
            logger.info("Logger repository configured successfully.");
            final LoggingEventHandler handler = new LoggingEventHandler(socket, repo, eventExecutor);
            handler.getSocketCloseListeners().add(this);
            eventHandlerMap.put(inetAddress, handler);
            handlerExecutor.execute(handler);
        } catch (UnauthorizedClientException e) {
            logger.warn(String.format("Unauthorized client %s rejected for reason: " + e.getMessage(),
                    e.getClient()));
            if (socket != null && !socket.isClosed()) {
                logger.info("Closing socket for rejected host.");
                try {
                    socket.close();
                } catch (IOException ioex) {
                    logger.error("Error closing client socket.", ioex);
                }
            }
        } catch (SocketException e) {
            // Check whether this is caused by a stop() invocation:
            // calling stop() closes server socket, which throws SocketException
            // from blocking accept() call
            if (serverSocket == null) {
                logger.info("Ignoring SocketException caused by stop() invocation.");
            } else {
                logger.error(e);
            }
        } catch (Exception e) {
            logger.error(e);
        }
    }
}

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./* w  w w. j  a  v a  2s.c o  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 - How long to wait for a connection to establish or a response from the target
 * @param object - The serializable object to send to the target
 * @return <code>Object</code> as output from the request
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized Object executeTcpRequest(final String hostName, final int portNumber,
        final int timeout, final Object object) throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeTcpRequest(final String hostName, final int portNumber, final int timeout, final Object object) throws UtilityException";

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

    Socket socket = null;
    Object resObject = null;

    try {
        synchronized (new Object()) {
            if (StringUtils.isEmpty(InetAddress.getByName(hostName).toString())) {
                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);
            }

            ObjectOutputStream objectOut = new ObjectOutputStream(socket.getOutputStream());

            if (DEBUG) {
                DEBUGGER.debug("ObjectOutputStream: {}", objectOut);
            }

            objectOut.writeObject(object);

            resObject = new ObjectInputStream(socket.getInputStream()).readObject();

            if (DEBUG) {
                DEBUGGER.debug("resObject: {}", resObject);
            }

            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);
    } catch (ClassNotFoundException cnfx) {
        throw new UtilityException(cnfx.getMessage(), cnfx);
    } 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);
        }
    }

    return resObject;
}