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:info.varden.irclinqed.dcc.FileSendThread.java

@Override
public void onIPSelected(String ipAddress) {
    try {//from  www. j av a2  s . c o  m
        if (!this.file.exists()) {
            return;
        }
        this.server = new ServerSocket(0);
        this.server.setSoTimeout(60000);
        DCCRequestPacket packet = null;
        String filename = this.file.getName();
        if (filename.split(" ").length > 1) {
            filename = "\"" + filename + "\"";
        }
        if (this.thread instanceof IRCThread) {
            packet = new DCCRequestPacket(this.il, (IRCThread) this.thread, this.target, DCCType.SEND, filename,
                    ipAddress, server.getLocalPort(), this.totalSize);
        } else if (this.thread instanceof DCCThread) {
            VirtualIRCThread thrd = new VirtualIRCThread(this.il, (DCCThread) this.thread);
            packet = new DCCRequestPacket(this.il, thrd, this.target, DCCType.SEND, filename, ipAddress,
                    server.getLocalPort(), this.totalSize);
        } else {
            this.server.close();
            return;
        }
        packet.send();
        if (this.cancel) {
            this.server.close();
            return;
        }
        this.message = "Waiting for connection...";
        Socket s = this.server.accept();
        this.overlay.unload();
        this.gfp = new GuiFileProgress(this.il, this);
        this.il.guiQueue.add(this.gfp);
        InputStream i = new FileInputStream(this.file);
        this.cos = new CountingOutputStream(s.getOutputStream());
        byte[] buff = new byte[1024];
        int k = -1;
        while ((k = i.read(buff)) > -1 && !this.cancel) {
            this.cos.write(buff, 0, k);
            s.getInputStream().read(new byte[4]);
        }
        s.shutdownInput();
        s.shutdownOutput();
        s.close();
        this.server.close();
        i.close();
        this.gfp.unload();
    } catch (SocketTimeoutException e) {
        this.overlay.unload();
        Util.extractUtil(this.thread).writeToChat(MessageType.DCC_ERROR, "File send timed out.");
    } catch (IOException e) {
        e.printStackTrace();
    }
    this.overlay.unload();
}

From source file:com.springrts.springls.ServerThread.java

public boolean redirectAndKill(Socket socket) {
    if (!context.getServer().isRedirectActive()) {
        return false;
    }//  w w w  . j  a v  a  2  s . c  om
    try {
        (new PrintWriter(socket.getOutputStream(), true)).println(
                String.format("REDIRECT %s", context.getServer().getRedirectAddress().getHostAddress()));
        socket.close();
    } catch (IOException ex) {
        return false;
    }
    return true;
}

From source file:com.shonshampain.streamrecorder.util.StreamProxy.java

private void startOver(InputStream data, Socket client, FailType type, Exception e) throws IOException {
    if (data != null) {
        Logger.e(TAG, "Closing data connection");
        data.close();//w  w w .  j  av  a 2  s .  co m
    }
    if (client != null && !client.isClosed()) {
        Logger.e(TAG, "Closing client connection");
        client.close();
    }
    ++retryCount;
    switch (type) {
    case Stall:
        Logger.e(TAG, "Stream has stalled, rethrottling(" + retryCount + ") the data connection");
        break;
    case Unexpected:
        Logger.e(TAG, "Unexpected exception: " + e.getLocalizedMessage() + " retrying(" + retryCount + ")");
        break;
    case CantDownload:
        Logger.e(TAG, "Cannot download, retrying(" + retryCount + ")");
        break;
    case SocketAccept:
        Logger.e(TAG, "Cannot accept on the socket, retrying(" + retryCount + ")");
        break;
    }
    if (retryCount == MAX_RETRIES) {
        Logger.e(TAG, "Retry count exceeded, stopping stream service");
        StreamManager.getInstance().stop(StreamRecorderApplication.getContext());
    } else {
        EventBus.getDefault().post(new ThrottleStreamRequest());
    }
}

From source file:com.honnix.cheater.admin.AdminServer.java

public void run() {
    while (true) {
        synchronized (lock) {
            if (!isStarted) {
                break;
            }/*from  www  . j a va 2 s. co  m*/
        }

        Socket clientSocket = null;

        try {
            clientSocket = serverSocket.accept();
        } catch (SocketException e) {
            // Here we can assume that if there is SocketException, it means
            // the socket has been closed.
            break;
        } catch (IOException e) {
            LOG.error("Failed accepting admin socket connection.", e);

            continue;
        }

        if (hasClient) {
            try {
                PrintWriter pw = new PrintWriter(clientSocket.getOutputStream());

                pw.println("Someone else is administrating me.");
                pw.flush();

                clientSocket.close();
            } catch (IOException e) {
                LOG.warn("Error operating client socket.", e);
            }
        } else {
            hasClient = true;

            new AdminClient(this, clientSocket).start();
        }
    }
}

From source file:com.alibaba.wasp.zookeeper.ZKUtil.java

/**
 * Gets the statistics from the given server.
 *
 * @param server//from  ww w  .ja v a 2 s. com
 *          The server to get the statistics from.
 * @param timeout
 *          The socket timeout to use.
 * @return The array of response strings.
 * @throws java.io.IOException
 *           When the socket communication fails.
 */
public static String[] getServerStats(String server, int timeout) throws IOException {
    String[] sp = server.split(":");
    if (sp == null || sp.length == 0) {
        return null;
    }

    String host = sp[0];
    int port = sp.length > 1 ? Integer.parseInt(sp[1]) : HConstants.DEFAULT_ZOOKEPER_CLIENT_PORT;

    Socket socket = new Socket();
    InetSocketAddress sockAddr = new InetSocketAddress(host, port);
    socket.connect(sockAddr, timeout);

    socket.setSoTimeout(timeout);
    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out.println("stat");
    out.flush();
    ArrayList<String> res = new ArrayList<String>();
    while (true) {
        String line = in.readLine();
        if (line != null) {
            res.add(line);
        } else {
            break;
        }
    }
    socket.close();
    return res.toArray(new String[res.size()]);
}

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

private void closeQuietly(Socket socket) {
    if (socket != null) {
        try {/*w  w w.j av  a  2  s . c om*/
            socket.close();
        } catch (IOException e) {
        }
    }
}

From source file:catalina.startup.Catalina.java

/**
 * Stop an existing server instance.//w  ww . java2 s.  com
 */
protected void stop() {

    // Create and execute our Digester
    Digester digester = createStopDigester();
    File file = configFile();
    try {
        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 {
        Socket socket = new Socket("127.0.0.1", server.getPort());
        OutputStream stream = socket.getOutputStream();
        String shutdown = server.getShutdown();
        for (int i = 0; i < shutdown.length(); i++)
            stream.write(shutdown.charAt(i));
        stream.flush();
        stream.close();
        socket.close();
    } catch (IOException e) {
        System.out.println("Catalina.stop: " + e);
        e.printStackTrace(System.out);
        System.exit(1);
    }

}

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

/**
 * Handle Job. Implementation of ThreadPool.handle(), calls handleConnection.
 * /*from w  w w.j  a  v  a 2 s  .  co  m*/
 * @param job A Connection.
 */
public void handle(Object job) {
    Socket socket = (Socket) job;
    try {
        if (_tcpNoDelay)
            socket.setTcpNoDelay(true);
        handleConnection(socket);
    } catch (Exception e) {
        log.debug("Connection problem", e);
    } finally {
        try {
            socket.close();
        } catch (Exception e) {
            log.debug("Connection problem", e);
        }
    }
}

From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientSSLConnectionFactory.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.ja  v a 2  s .co  m*/
    }
    try {
        if (connectTimeout > 0 && sock.getSoTimeout() == 0) {
            sock.setSoTimeout(connectTimeout);
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connecting socket to " + remoteAddress + " with timeout " + connectTimeout);
        }
        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;
        this.log.debug("Starting handshake");
        sslsock.startHandshake();
        verifyHostname(sslsock, host.getHostName());
        return sock;
    } else {
        return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
    }
}