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:io.aino.agents.core.AgentIntegrationTest.java

private boolean isReachable(String host, int port, int timeout) throws IOException {
    SocketAddress proxyAddress = new InetSocketAddress(host, port);
    Socket socket = new Socket();
    try {// ww w.  ja va 2s .c  om
        socket.connect(proxyAddress, timeout);
        //System.out.println("Connected to: " + host + ":" + port);
        return socket.isConnected();
    } catch (IOException e) {
        System.out.println("Could not connect to: " + host + ":" + port);
        return false;
    } finally {
        if (socket.isConnected()) {
            //System.out.println("Closing connection to: " + host + ":" + port);
            socket.close();
            //System.out.println("Disconnected: " + host + ":" + port);
        }
    }
}

From source file:com.mirth.connect.connectors.mllp.MllpMessageDispatcher.java

public void doDispose(Socket socket) {
    monitoringController.updateStatus(connector, connectorType, Event.DISCONNECTED, socket);
    if (null != socket && !socket.isClosed()) {
        try {/*from www  .j a  va  2s .c o  m*/
            socket.close();
            connectedSockets.values().remove(socket);
            socket = null;
        } catch (IOException e) {
            logger.debug("ConnectedSocked close raised exception. Reason: " + e.getMessage());
        }
    }

}

From source file:com.bfd.harpc.heartbeat.HeartBeatTask.java

/**
 * socket?//from   www  .j a  v a2  s . co  m
 * <p>
 * 
 * @param serverNode
 */
private boolean checkSocket(ServerNode serverNode) {
    boolean isValid = false;
    Socket socket = null;
    try {
        InetSocketAddress socketAddress = new InetSocketAddress(serverNode.getIp(), serverNode.getPort());
        socket = new Socket();
        socket.connect(socketAddress, heartbeatTimeout);
        isValid = true;
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Heartbeat to remote " + serverNode.genAddress() + " success!");
        }
    } catch (IOException e) {
        LOGGER.warn("Heartbeat to remote " + serverNode.genAddress() + " failure!", e);
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                LOGGER.warn(e.getMessage(), e);
            }
        }
    }
    return isValid;
}

From source file:ru.codemine.ccms.counters.kondor.KondorClient.java

private File ftpDownload(Shop shop) {
    String login = settingsService.getCountersKondorFtpLogin();
    String pass = settingsService.getCountersKondorFtpPassword();
    String ip = shop.getProvider().getIp();
    String tmpFileName = settingsService.getStorageRootPath()
            + DateTime.now().toString("YYYYMMdd-s" + shop.getId());
    try {/*  w w w  .j  a  v  a2s .  c om*/
        log.debug("Starting ftp session...");

        Socket manageSocket = new Socket();
        manageSocket.connect(new InetSocketAddress(ip, 21), 3000);
        BufferedReader in = new BufferedReader(new InputStreamReader(manageSocket.getInputStream()));
        PrintWriter out = new PrintWriter(manageSocket.getOutputStream(), true);
        String ftpAnswer;

        ftpAnswer = in.readLine();
        log.debug("FTP greetings: " + ftpAnswer);

        out.println("USER " + login);
        ftpAnswer = in.readLine();
        log.debug("FTP USER command responce: " + ftpAnswer);

        out.println("PASS " + pass);
        String afterAuth = in.readLine();
        log.debug("FTP PASS command responce: " + afterAuth);

        out.println("PASV");
        String pasvResponce = in.readLine();
        log.debug("FTP: PASV command responce: " + pasvResponce);

        if (pasvResponce.startsWith("227 (")) {
            pasvResponce = pasvResponce.substring(5);
            List<String> parsedPasv = new ArrayList<>(Arrays.asList(pasvResponce.split(",")));
            String p4 = parsedPasv.get(4);
            String p5 = parsedPasv.get(5).replace(")", "");
            int port = Integer.parseInt(p4) * 256 + Integer.parseInt(p5);

            log.debug("FTP: Recieved port: " + port);

            Socket dataSocket = new Socket();
            dataSocket.connect(new InetSocketAddress(ip, port), 3000);
            InputStream dataIn = dataSocket.getInputStream();
            FileOutputStream dataOut = new FileOutputStream(tmpFileName);

            out.println("RETR total.dbf");
            ftpAnswer = in.readLine();
            log.debug("FTP RETR command responce: " + ftpAnswer);

            IOUtils.copy(dataIn, dataOut);

            dataOut.flush();
            dataOut.close();
            dataSocket.close();
        } else {
            if (afterAuth.startsWith("530")) {
                log.warn(
                        "     ?, : "
                                + shop.getName());

            } else {
                log.warn(
                        " ?     PASV, : "
                                + shop.getName());
            }

        }

        out.println("QUIT");
        ftpAnswer = in.readLine();
        log.debug("FTP QUIT command responce: " + ftpAnswer);

        manageSocket.close();
    } catch (Exception e) {
        log.warn(
                "?   ? ?   "
                        + shop.getName() + ",  : " + e.getMessage());
    }

    return new File(tmpFileName);
}

From source file:net.mohatu.bloocoin.miner.RegisterClass.java

private void register() {
    try {//  w  ww . j a  v  a2  s. c  om
        String result = new String();
        Socket sock = new Socket(this.url, this.port);
        String command = "{\"cmd\":\"register" + "\",\"addr\":\"" + addr + "\",\"pwd\":\"" + key + "\"}";
        DataInputStream is = new DataInputStream(sock.getInputStream());
        DataOutputStream os = new DataOutputStream(sock.getOutputStream());
        os.write(command.getBytes());
        os.flush();

        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            result += inputLine;
        }

        is.close();
        os.close();
        sock.close();
        System.out.println(result);
        if (result.contains("\"success\": true")) {
            System.out.println("Registration successful: " + addr);
            saveBloostamp();
        } else if (result.contains("\"success\": false")) {
            System.out.println("Result: Failed");
            MainView.updateStatusText("Registration failed. ");
            System.exit(0);
        }
    } catch (UnknownHostException e) {
        System.out.println("Error: Unknown host.");
    } catch (IOException e) {
        System.out.println("Error: Network error.");
    }
}

From source file:com.adito.jdbc.hsqldb.EmbeddedHSQLDBServer.java

void waitForServerToStop() {
    if (serverMode) {
        Socket s = null;
        String addr = server.getAddress().equals("0.0.0.0") ? "127.0.0.1" : server.getAddress();
        if (log.isInfoEnabled())
            log.info("Waiting for HSQLDB to stop accepting connections on " + addr + ":" + server.getPort());
        int i = 0;
        for (; i < 30; i++) {
            try {
                s = new Socket(addr, server.getPort());
                try {
                    s.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }/*from   w  w  w .ja  v a  2 s  .  c  o m*/
                s = null;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ie) {
                }
            } catch (IOException ioe) {
                break;
            } finally {
                if (s != null) {
                    try {
                        s.close();
                    } catch (Exception e) {
                    }
                    s = null;
                }
            }
        }
        if (i == 30) {
            throw new IllegalStateException("The HSQLDB server has not stopped after 30 seconds.");
        } else {
            if (log.isInfoEnabled())
                log.info("HSQLDB is now stopped.");
        }
    }
}

From source file:net.mohatu.bloocoin.miner.RegCustom.java

private void register() {
    try {/*  ww  w.  j ava  2s  . co  m*/
        String result = new String();
        Socket sock = new Socket(this.url, this.port);
        String command = "{\"cmd\":\"register" + "\",\"addr\":\"" + addr + "\",\"pwd\":\"" + key + "\"}";
        DataInputStream is = new DataInputStream(sock.getInputStream());
        DataOutputStream os = new DataOutputStream(sock.getOutputStream());
        os.write(command.getBytes());
        os.flush();

        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            result += inputLine;
        }

        is.close();
        os.close();
        sock.close();
        System.out.println(result);
        if (result.contains("\"success\": true")) {
            System.out.println("Registration successful: " + addr);
            saveBloostamp();
        } else if (result.contains("\"success\": false")) {
            System.out.println("Result: Failed");
            JOptionPane.showMessageDialog(Main.scrollPane,
                    "Registration failed.\nCheck your network connection", "Registration Failed",
                    JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.yeetor.minitouch.Minitouch.java

private Thread startInitialThread(final String host, final int port) {
    Thread thread = new Thread(new Runnable() {
        @Override//from   www.ja va2s  .  co m
        public void run() {
            int tryTime = 200;
            while (true) {
                Socket socket = null;
                byte[] bytes = new byte[256];
                try {
                    socket = new Socket(host, port);
                    InputStream inputStream = socket.getInputStream();
                    OutputStream outputStream = socket.getOutputStream();
                    int n = inputStream.read(bytes);

                    if (n == -1) {
                        Thread.sleep(10);
                        socket.close();
                    } else {
                        minitouchSocket = socket;
                        minitouchOutputStream = outputStream;
                        onStartup(true);
                        break;
                    }
                } catch (Exception ex) {
                    if (socket != null) {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    continue;
                }
                tryTime--;
                if (tryTime == 0) {
                    onStartup(false);
                    break;
                }
            }
        }
    });
    thread.start();
    return thread;
}

From source file:jhttpp2.Jhttpp2HTTPSession.java

public Jhttpp2HTTPSession(Jhttpp2Server server, Socket client) {
    try {/* w ww.j av a2s  . c  o  m*/
        in = new Jhttpp2ClientInputStream(server, this, client.getInputStream());// ,true);
        out = new BufferedOutputStream(client.getOutputStream());
        this.server = server;
        this.client = client;
    } catch (IOException e_io) {
        try {
            client.close();
        } catch (IOException e_io2) {
            log.debug("Error while closing client (kinda expected)" + e_io);
        }
        log.warn("Error while creating IO-Streams: ", e_io);
        return;
    }
    start();
}

From source file:com.jkoolcloud.tnt4j.streams.utils.Utils.java

/**
 * Close an socket without exceptions.// w w  w  . ja  v a 2s  .  c  om
 * <p>
 * For Java 6 backward comparability.
 *
 * @param socket
 *            socket to close
 */
public static void close(Socket socket) {
    if (socket != null) {
        try {
            socket.close();
        } catch (IOException exc) {

        }
    }
}