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:com.envirover.spl.SPLGroungControlTest.java

@Test
public void testMTMessagePipeline() {
    System.out.println("MT TEST: Testing MT message pipeline...");

    Socket client = null;
    DataOutputStream out = null;//ww w  .  ja  v  a  2s .  co  m

    try {
        System.out.printf("MT TEST: Connecting to tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(),
                config.getMAVLinkPort());
        System.out.println();

        client = new Socket(InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());

        System.out.printf("MT TEST: Connected to tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(),
                config.getMAVLinkPort());
        System.out.println();

        out = new DataOutputStream(client.getOutputStream());

        MAVLinkPacket packet = getSamplePacket();
        out.write(packet.encodePacket());
        out.flush();

        System.out.printf("MT TEST: MAVLink message sent: msgid = %d", packet.msgid);
        System.out.println();

        Thread.sleep(5000);

        System.out.println("MT TEST: Complete.");
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (out != null)
                out.close();

            if (client != null)
                client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.buaa.cfs.utils.NetUtils.java

/**
 * Like {@link NetUtils#connect(Socket, SocketAddress, int)} but also takes a local address and port to bind the
 * socket to.//from ww  w  .j  a  va 2  s  .  c  om
 *
 * @param socket
 * @param endpoint  the remote address
 * @param localAddr the local address to bind the socket to
 * @param timeout   timeout in milliseconds
 */
public static void connect(Socket socket, SocketAddress endpoint, SocketAddress localAddr, int timeout)
        throws IOException {
    if (socket == null || endpoint == null || timeout < 0) {
        throw new IllegalArgumentException("Illegal argument for connect()");
    }

    SocketChannel ch = socket.getChannel();

    if (localAddr != null) {
        Class localClass = localAddr.getClass();
        Class remoteClass = endpoint.getClass();
        Preconditions.checkArgument(localClass.equals(remoteClass),
                "Local address %s must be of same family as remote address %s.", localAddr, endpoint);
        socket.bind(localAddr);
    }

    try {
        if (ch == null) {
            // let the default implementation handle it.
            socket.connect(endpoint, timeout);
        } else {
            //        SocketIOWithTimeout.connect(ch, endpoint, timeout);
        }
    } catch (SocketTimeoutException ste) {
        //      throw new ConnectTimeoutException(ste.getMessage());
    }

    // There is a very rare case allowed by the TCP specification, such that
    // if we are trying to connect to an endpoint on the local machine,
    // and we end up choosing an ephemeral port equal to the destination port,
    // we will actually end up getting connected to ourself (ie any data we
    // send just comes right back). This is only possible if the target
    // daemon is down, so we'll treat it like connection refused.
    if (socket.getLocalPort() == socket.getPort() && socket.getLocalAddress().equals(socket.getInetAddress())) {
        LOG.info("Detected a loopback TCP socket, disconnecting it");
        socket.close();
        throw new ConnectException("Localhost targeted connection resulted in a loopback. "
                + "No daemon is listening on the target port.");
    }
}

From source file:com.gargoylesoftware.htmlunit.NoHttpResponseTest.java

@Override
public void run() {
    try {/* www.j av a2s  .co m*/
        serverSocket_ = new ServerSocket(port_);
        started_.set(true);
        LOG.info("Starting listening on port " + port_);
        while (!shutdown_) {
            final Socket s = serverSocket_.accept();
            final BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));

            final CharBuffer cb = CharBuffer.allocate(5000);
            br.read(cb);
            cb.flip();
            final String in = cb.toString();
            cb.rewind();

            final RawResponseData responseData = getResponseData(in);

            if (responseData == null || responseData.getStringContent() == DROP_CONNECTION) {
                LOG.info("Closing impolitely in & output streams");
                s.getOutputStream().close();
            } else {
                final PrintWriter pw = new PrintWriter(s.getOutputStream());
                pw.println("HTTP/1.0 " + responseData.getStatusCode() + " " + responseData.getStatusMessage());
                for (final NameValuePair header : responseData.getHeaders()) {
                    pw.println(header.getName() + ": " + header.getValue());
                }
                pw.println();
                pw.println(responseData.getStringContent());
                pw.println();
                pw.flush();
                pw.close();
            }
            br.close();
            s.close();
        }
    } catch (final SocketException e) {
        if (!shutdown_) {
            LOG.error(e);
        }
    } catch (final IOException e) {
        LOG.error(e);
    } finally {
        LOG.info("Finished listening on port " + port_);
    }
}

From source file:com.techcavern.pircbotz.IdentServer.java

/**
 * Waits for a client to connect to the ident server before making an
 * appropriate response.//from w  ww . jav  a 2  s.co m
 */
public void run() {
    log.info("IdentServer running on port " + serverSocket.getLocalPort());
    //TODO: Multi-thread this
    while (!serverSocket.isClosed()) {
        Socket socket = null;
        try {
            socket = serverSocket.accept();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(socket.getInputStream(), encoding));
            OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream(), encoding);
            InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();

            //Read first line and process
            String line = reader.readLine();
            String response = handleNextConnection(remoteAddress, line);
            if (response != null) {
                writer.write(response);
                writer.flush();
            }
        } catch (Exception e) {
            if (serverSocket.isClosed()) {
                log.debug("Server socket closed, exiting connection loop");
                return;
            } else
                //This is not from the server socket closing
                throw new RuntimeException("Exception encountered when opening user socket");
        } finally {
            //Close user socket
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                throw new RuntimeException("Exception encountered when closing user socket");
            }
        }
    }

    //Done with connection loop, can safely close the socket now
    if (!serverSocket.isClosed())
        try {
            close();
        } catch (IOException e) {
            log.error("Cannot close IdentServer socket", e);
        }
}

From source file:com.esri.geoevent.test.tools.RunTcpInBdsOutTest.java

public void send(String server, Integer port, Long numEvents, Integer rate, String data_file) {

    BufferedReader br = null;/*from   ww  w  .  j  a  v  a2  s . co  m*/
    ArrayList<String> lines = new ArrayList<>();
    LocalDateTime st = null;

    try {

        // Read the file into String array
        br = new BufferedReader(new FileReader(data_file));

        String line = null;
        while ((line = br.readLine()) != null) {
            lines.add(line);
        }

        Socket sckt = new Socket(server, port);
        OutputStream os = sckt.getOutputStream();

        Integer cnt = 0;

        st = LocalDateTime.now();

        Double ns_delay = 1000000000.0 / (double) rate;

        long ns = ns_delay.longValue();
        if (ns < 0) {
            ns = 0;
        }

        int i = 0;
        int j = 0;

        while (i < numEvents) {
            i++;
            j++;
            if (j >= lines.size()) {
                j = 0;
            }
            line = lines.get(j) + "\n";

            final long stime = System.nanoTime();

            long etime = 0;
            do {
                etime = System.nanoTime();
            } while (stime + ns >= etime);

            os.write(line.getBytes());
            os.flush();

        }

        LocalDateTime et = LocalDateTime.now();
        if (st != null) {
            et = LocalDateTime.now();

            Duration delta = Duration.between(st, et);

            Double elapsed_seconds = (double) delta.getSeconds() + delta.getNano() / 1000000000.0;

            send_rate = (double) numEvents / elapsed_seconds;
        }

        sckt.close();
        os = null;

    } catch (Exception e) {
        System.err.println(e.getMessage());
        send_rate = -1.0;
    } finally {
        try {
            br.close();
        } catch (Exception e) {
            //
        }

        this.send_rate = send_rate;

    }

}

From source file:br.com.i9torpedos.model.service.serverSocket.DSSocketSIM1.java

@Override
public void run() {

    try {//www.  jav a 2 s  .c  o m
        while (true) {
            Socket socket = server.accept();
            log.info("Cliente conectado  " + socket.getInetAddress());

            try {

                PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
                printWriter.println(conectou);
                log.info("Sinal de autenticao enviado para o Cliente  " + new Date().toString());

                //Faz verificao no fluxo de entrada do Objeto
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());

                try {

                    //faz a leitura do Objeto de entrada
                    Object readObject = objectInputStream.readObject();

                    if (readObject instanceof SendSMSMessage) {

                        try {

                            SendSMSMessage smsMessage = (SendSMSMessage) readObject;

                            // Thread.sleep(random.nextInt(10000));

                            ponte.set(smsMessage);
                            Thread t = new Thread(new ConsumerSendSMSMessage(ponte),
                                    "PONTE_ASYNC_DSSOCKETSIM1");
                            t.start();

                            listaSMS.add(smsMessage);

                            objectInputStream.close();
                            socket.close();

                            if (listaSMS.size() > 0 && !listaSMS.isEmpty()) {

                                DServiceModem1 md1 = new DServiceModem1(listaSMS, 1000);
                                new Thread(md1, "MODEM 1").start();
                                listaSMS.clear();

                            }

                        } catch (InterruptedException ex) {
                            Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }

                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
                }

            } catch (IOException ex) {
                Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    socket.close();
                } catch (IOException ex) {
                    Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            server.close();
        } catch (IOException ex) {
            Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:com.adito.agent.client.tunneling.LocalTunnelServer.java

void tunnelTCP() {
    stopping = false;//from   ww w.  j a va2s. c  o m
    Socket socket = null;
    try {

        listening = true;

        while (listening) {
            try {
                socket = server.accept();
                if (!listening || (socket == null)) {
                    break;
                }

                try {
                    // Open an SSL tunnel and connect the socket to the tunnel
                    LocalTunnelConnection vpntunnel = new LocalTunnelConnection(this,
                            openChannel(listeningSocketConfiguration), socket, getTunnel(), txListener,
                            rxListener);
                    vpntunnel.addListener(this);
                    vpntunnel.start();

                } catch (Throwable ex) {
                    // #ifdef DEBUG
                    log.info(
                            Messages.getString("LocalTunnelConnectionListener.failedToConnectTunnelingRequest"), //$NON-NLS-1$
                            ex);
                    // #endif
                    try {
                        socket.close();
                    } catch (IOException ioe) {
                    }

                    if (listeningSocketConfiguration.isTemporarySingleConnect()) {
                        throw ex;
                    }
                }

                if (listeningSocketConfiguration.isTemporarySingleConnect()) {
                    // #ifdef DEBUG
                    log.info(Messages.getString("LocalTunnelConnectionListener.notAcceptingMoreAsTemp")); //$NON-NLS-1$
                    // #endif
                    break;
                }
            } catch (IOException ioe) {
                // #ifdef DEBUG
                log.info(Messages.getString("LocalTunnelConnectionListener.failedToConnectTunnelingRequest"), //$NON-NLS-1$
                        ioe);
                // #endif
            }
        }
    } catch (Throwable ex) {
        if (!stopping) {
            // #ifdef DEBUG
            log.info(Messages.getString("LocalTunnelConnectionListener.connectionListenerThreadFailed"), ex); //$NON-NLS-1$
            // #endif
            stop();
        }
    }
}

From source file:gov.nasa.arc.spife.europa.clientside.EuropaServerManager.java

private int findPort(int startAt) {
    Socket temp = null;
    for (int testPort = startAt; testPort < startAt + 1000; ++testPort) {
        try {/*  w  w w .  j  a  va  2  s. c  o  m*/
            writeLog("[findPort] Testing port " + testPort);

            temp = new Socket(EuropaServerManagerConfig.LOCALHOST, testPort);
            if (temp.isBound())
                writeLog("[findPort] Successfully bound port.  Skipping " + testPort);
            else
                writeLog("[findPort] Port " + testPort + " is in use.  Moving on.");
        } catch (IOException ioe) {
            if (ioe instanceof ConnectException)
                return testPort;
        }
        //you cannot get ye port
        catch (SecurityException se) {
            writeLog("[findPort] Security exception testing a port.  Returning -1.", DynamicEuropaLogger.ERROR);
            return -1;
        } finally {
            try {
                if (temp != null)
                    temp.close();
            } catch (Exception e) {
                writeLog("[findPort] Failed to close a test-socket.", DynamicEuropaLogger.ERROR);
            }
        }
    }
    writeLog("[findPort] Exhausted 1000 possible ports.  Returning -1.", DynamicEuropaLogger.ERROR);
    return -1;
}

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

private void submit() {
    for (int i = 0; i < solved.size(); i++) {
        try {/*from   ww w  . j ava 2 s. co  m*/
            Socket sock = new Socket(this.url, this.port);
            String result = new String();
            DataInputStream is = new DataInputStream(sock.getInputStream());
            DataOutputStream os = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            solution = solved.get(i);
            hash = DigestUtils.sha512Hex(solution);

            String command = "{\"cmd\":\"check" + "\",\"winning_string\":\"" + solution
                    + "\",\"winning_hash\":\"" + hash + "\",\"addr\":\"" + MainView.getAddr() + "\"}";
            os = new DataOutputStream(sock.getOutputStream());
            os.write(command.getBytes());

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

            if (result.contains("\"success\": true")) {
                System.out.println("Result: Submitted");
                MainView.updateStatusText(solution + " submitted");
                Thread gc = new Thread(new CoinClass());
                gc.start();
            } else if (result.contains("\"success\": false")) {
                System.out.println("Result: Failed");
                MainView.updateStatusText("Submission of " + solution + " failed, already exists!");
            }
            is.close();
            os.close();
            os.flush();
            sock.close();
        } catch (UnknownHostException e) {
            MainView.updateStatusText("Submission of " + solution + " failed, connection failed!");
        } catch (IOException e) {
            MainView.updateStatusText("Submission of " + solution + " failed, connection failed!");
        }
    }
    Thread gc = new Thread(new CoinClass());
    gc.start();
}

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

private void submit() {
    for (int i = 0; i < solved.size(); i++) {
        try {//from w  w w.  j a v a 2 s. co  m
            Socket sock = new Socket(this.url, this.port);
            String result = new String();
            DataInputStream is = new DataInputStream(sock.getInputStream());
            DataOutputStream os = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            solution = solved.get(i);
            hash = DigestUtils.sha512Hex(solution);

            String command = "{\"cmd\":\"check" + "\",\"winning_string\":\"" + solution
                    + "\",\"winning_hash\":\"" + hash + "\",\"addr\":\"" + Main.getAddr() + "\"}";
            os = new DataOutputStream(sock.getOutputStream());
            os.write(command.getBytes());

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

            if (result.contains("\"success\": true")) {
                System.out.println("Result: Submitted");
                Main.updateStatusText(solution + " submitted", Color.blue);
                Thread gc = new Thread(new Coins());
                gc.start();
            } else if (result.contains("\"success\": false")) {
                System.out.println("Result: Failed");
                Main.updateStatusText("Submission of " + solution + " failed, already exists!", Color.red);
            }
            is.close();
            os.close();
            os.flush();
            sock.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            Main.updateStatusText("Submission of " + solution + " failed, connection failed!", Color.red);
        } catch (IOException e) {
            e.printStackTrace();
            Main.updateStatusText("Submission of " + solution + " failed, connection failed!", Color.red);
        }
    }
    Thread gc = new Thread(new Coins());
    gc.start();
}