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:de.vanita5.twittnuker.util.net.ssl.HostResolvedSSLConnectionSocketFactory.java

@Override
public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host,
        final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context)
        throws IOException {
    Args.notNull(host, "HTTP host");
    Args.notNull(remoteAddress, "Remote address");
    final Socket sock = socket != null ? socket : createSocket(context);
    if (localAddress != null) {
        sock.bind(localAddress);/*  w w w .  j a v  a 2 s. co m*/
    }
    try {
        sock.connect(remoteAddress, connectTimeout);
    } catch (final IOException ex) {
        try {
            sock.close();
        } catch (final IOException ignore) {
        }
        throw ex;
    }
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        final SSLSocket sslsock = (SSLSocket) sock;
        sslsock.startHandshake();
        verifyHostname(sslsock, host.getHostName(), context);
        return sock;
    } else
        return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
}

From source file:com.bmwcarit.barefoot.tracker.TrackerServerTest.java

public void sendSample(InetAddress host, int port, JSONObject sample) throws InterruptedException, IOException {
    int trials = 120;
    int timeout = 500;
    Socket client = null;

    while (client == null || !client.isConnected()) {
        try {//  ww  w  . j  a v  a2 s . c o  m
            client = new Socket(host, port);
        } catch (IOException e) {
            Thread.sleep(timeout);

            if (trials == 0) {
                logger.error(e.getMessage());
                client.close();
                throw new IOException();
            } else {
                trials -= 1;
            }
        }
    }

    PrintWriter writer = new PrintWriter(client.getOutputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
    writer.println(sample.toString());
    writer.flush();

    String code = reader.readLine();
    assertEquals("SUCCESS", code);
}

From source file:ext.services.network.TestNetworkUtils.java

/**
 * Test get connection url proxy with proxy.
 * /*from  w  ww . j  ava 2s  .  co m*/
 *
 * @throws Exception the exception
 */
public void testGetConnectionURLProxyWithProxy() throws Exception {
    final ServerSocket socket = new ServerSocket(PROXY_PORT);
    Thread thread = new Thread("ProxySocketAcceptThread") {
        @Override
        public void run() {
            try {
                while (!bStop) {
                    Socket sock = socket.accept();
                    Log.debug("Accepted connection, sending back garbage and close socket...");
                    sock.getOutputStream().write(1);
                    sock.close();
                }
            } catch (IOException e) {
                Log.error(e);
            }
        }
    };
    thread.setDaemon(true); // to finish tests even if this is still running
    thread.start();
    Log.debug("Using local port: " + socket.getLocalPort());
    try {
        // useful content when inet access is allowed
        Conf.setProperty(Const.CONF_NETWORK_NONE_INTERNET_ACCESS, "false");
        HttpURLConnection connection = NetworkUtils.getConnection(new java.net.URL(URL),
                new Proxy(Type.SOCKS, "localhost", socket.getLocalPort(), "user", "password"));
        assertNotNull(connection);
        connection.disconnect();
    } finally {
        bStop = true;
        socket.close();
        thread.join();
    }
}

From source file:com.leetchi.api.client.ssl.SSLConnectionSocketFactory.java

public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host,
        final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context)
        throws IOException {
    Args.notNull(host, "HTTP host");
    Args.notNull(remoteAddress, "Remote address");
    final Socket sock = socket != null ? socket : createSocket(context);
    if (localAddress != null) {
        sock.bind(localAddress);/*from  www . j a v  a  2 s .c om*/
    }
    try {
        sock.connect(remoteAddress, connectTimeout);
    } catch (final IOException ex) {
        try {
            sock.close();
        } catch (final IOException ignore) {
        }
        throw ex;
    }
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        final SSLSocket sslsock = (SSLSocket) sock;
        sslsock.startHandshake();
        verifyHostname(sslsock, host.getHostName());
        return sock;
    } else {
        return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
    }
}

From source file:NanoHTTPD.java

private static final void safeClose(Socket closeable) {
    if (closeable != null) {
        try {/*from w  w  w  .j  a v  a  2 s  .c o m*/
            closeable.close();
        } catch (IOException e) {
        }
    }
}

From source file:org.mycard.net.network.AndroidHttpClientConnection.java

public void shutdown() throws IOException {
    this.open = false;
    Socket tmpsocket = this.socket;
    if (tmpsocket != null) {
        tmpsocket.close();
    }//from  ww w.ja v  a  2 s  .c  om
}

From source file:com.bmwcarit.barefoot.tracker.TrackerServerTest.java

public MatcherKState requestState(InetAddress host, int port, String id)
        throws JSONException, InterruptedException, IOException {
    int trials = 120;
    int timeout = 500;
    Socket client = null;

    while (client == null || !client.isConnected()) {
        try {//from   w w w .  j  av a  2s.c  om
            client = new Socket(host, port);
        } catch (IOException e) {
            Thread.sleep(timeout);

            if (trials == 0) {
                logger.error(e.getMessage());
                client.close();
                throw new IOException();
            } else {
                trials -= 1;
            }
        }
    }

    JSONObject json = new JSONObject();
    json.put("id", id);

    PrintWriter writer = new PrintWriter(client.getOutputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
    writer.println(json.toString());
    writer.flush();

    String code = reader.readLine();
    assertEquals("SUCCESS", code);

    String response = reader.readLine();
    client.close();

    return new MatcherKState(new JSONObject(response), new MatcherFactory(TrackerControl.getServer().getMap()));
}

From source file:org.npr.android.test.HttpServer.java

private void processRequest(DataSource dataSource, Socket client) throws IllegalStateException, IOException {
    if (dataSource == null) {
        Log.e(TAG, "Invalid (null) resource.");
        client.close();
        return;//from  w  w  w .j a  v  a  2  s .  com
    }

    Log.d(TAG, "setting response headers");
    StringBuilder httpString = new StringBuilder();
    httpString.append(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK"));
    httpString.append("\n");

    httpString.append("Content-Type: ").append(dataSource.getContentType());
    httpString.append("\n");

    // Some content (e.g. streams) does not define a length
    long length = dataSource.getContentLength();
    if (length >= 0) {
        httpString.append("Content-Length: ").append(length);
        httpString.append("\n");
    }

    httpString.append("\n");
    Log.d(TAG, "headers done");

    InputStream data = null;
    try {
        data = dataSource.createInputStream();
        byte[] buffer = httpString.toString().getBytes();
        int readBytes;
        Log.d(TAG, "writing to client");
        client.getOutputStream().write(buffer, 0, buffer.length);

        // Start sending content.
        byte[] buff = new byte[1024 * 50];
        while (isRunning) {
            readBytes = data.read(buff, 0, buff.length);
            if (readBytes == -1) {
                if (simulateStream) {
                    data.close();
                    data = dataSource.createInputStream();
                    readBytes = data.read(buff, 0, buff.length);
                    if (readBytes == -1) {
                        throw new IOException("Error re-opening data source for looping.");
                    }
                } else {
                    break;
                }
            }
            client.getOutputStream().write(buff, 0, readBytes);
        }
    } catch (SocketException e) {
        // Ignore when the client breaks connection
        Log.w(TAG, "Ignoring " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "Error getting content stream.", e);
    } catch (Exception e) {
        Log.e(TAG, "Error streaming file content.", e);
    } finally {
        if (data != null) {
            data.close();
        }
        client.close();
    }
}

From source file:org.jsnap.http.base.HttpServletRunner.java

public void reject(Socket s) {
    try {// w  w w  . j a va2 s  .co m
        HttpServerConnection connection = new HttpServerConnection();
        connection.bind(s, new DefaultHttpParams());
        HttpReject reject = new HttpReject(connection);
        reject.service(); // Calls HttpReject.doServiceImpl at some point.
    } catch (IOException ignore) {
        // Hard to handle at this point, just ignore.
    } finally {
        try {
            s.close();
        } catch (IOException e) {
            // Do not even bother to log.
        }
    }
}

From source file:org.mule.module.http.functional.listener.HttpListenerPersistentConnectionsTestCase.java

protected void assertConnectionClosesAfterTimeout(DynamicPort port, HttpVersion httpVersion)
        throws IOException, InterruptedException {
    Socket socket = new Socket("localhost", port.getNumber());
    sendRequest(socket, httpVersion);//from   w w w . j a  v  a 2 s .c om
    assertResponse(getResponse(socket), true);

    sendRequest(socket, httpVersion);
    assertResponse(getResponse(socket), true);

    Thread.sleep(3000);

    sendRequest(socket, httpVersion);
    assertResponse(getResponse(socket), false);

    socket.close();
}