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:eu.stratosphere.nephele.taskmanager.TaskManager.java

public static boolean tryToConnect(InetAddress fromAddress, SocketAddress toSocket, int timeout)
        throws IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Trying to connect to JobManager (" + toSocket + ") from local address " + fromAddress
                + " with timeout " + timeout);
    }//  w  ww .jav a  2  s  . c  o m
    boolean connectable = true;
    Socket socket = null;
    try {
        socket = new Socket();
        SocketAddress bindP = new InetSocketAddress(fromAddress, 0); // 0 = let the OS choose the port on this
        // machine
        socket.bind(bindP);
        socket.connect(toSocket, timeout);
    } catch (Exception ex) {
        LOG.info("Failed to determine own IP address from '" + fromAddress + "': " + ex.getMessage());
        if (LOG.isDebugEnabled()) {
            LOG.debug("Failed with exception", ex);
        }
        connectable = false;
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
    return connectable;
}

From source file:io.github.gsteckman.rpi_rest.SubscriptionManager.java

/**
 * Sends the provided message to the host and port specified in the URL object.
 * // ww  w.j  a v  a 2 s .  c  o  m
 * @param url
 *            Provides the host and port to which the message is sent via TCP.
 * @param message
 *            The message to send, including all headers and message body.
 * @throws IOException
 *             If an exception occured writing to the socket.
 */
private void sendNotify(final URL url, final String message) throws IOException {
    Socket sock = new Socket(url.getHost(), url.getPort());
    OutputStreamWriter out = new OutputStreamWriter(sock.getOutputStream());
    out.write(message);
    out.close();
    sock.close();
}

From source file:net.NetUtils.java

/**
 * This is a drop-in replacement for //from  w w w . j a  va 2s  .co m
 * {@link Socket#connect(SocketAddress, int)}.
 * In the case of normal sockets that don't have associated channels, this 
 * just invokes <code>socket.connect(endpoint, timeout)</code>. If 
 * <code>socket.getChannel()</code> returns a non-null channel,
 * connect is implemented using Hadoop's selectors. This is done mainly
 * to avoid Sun's connect implementation from creating thread-local 
 * selectors, since Hadoop does not have control on when these are closed
 * and could end up taking all the available file descriptors.
 * 
 * @see java.net.Socket#connect(java.net.SocketAddress, int)
 * 
 * @param socket
 * @param endpoint 
 * @param timeout - timeout in milliseconds
 */
public static void connect(Socket socket, SocketAddress endpoint, int timeout) throws IOException {
    if (socket == null || endpoint == null || timeout < 0) {
        throw new IllegalArgumentException("Illegal argument for connect()");
    }

    SocketChannel ch = socket.getChannel();

    if (ch == null) {
        // let the default implementation handle it.
        socket.connect(endpoint, timeout);
    } else {
        SocketIOWithTimeout.connect(ch, endpoint, timeout);
    }

    // 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:pl.edu.agh.ServiceConnection.java

/**
 * 1. Sends data to service: console password | service password | service id
 *///from  w  w  w . ja  va 2s.c om
public void connect(Service service) {
    try {
        LOGGER.info("Connecting to service: " + service);
        Socket socket = new Socket(service.getHost(), service.getPort());
        socket.setSoTimeout(300);
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        out.writeBytes(service.getPassword() + "|" + service.getId() + "\r\n");
        String response = in.readLine();

        in.close();
        out.close();
        socket.close();

        LOGGER.info("Service response: " + response);

    } catch (Exception e) {
        LOGGER.error("Error connecting with daemon: " + e.getMessage());
    }
}

From source file:Clases.cCifrado.java

public String pedirClave(String dato) {

    String clave = "";
    Scanner sc = new Scanner(System.in);
    Socket socket;
    try {/* ww  w.j a v a  2s  .co m*/
        String ipServidor = receptor;
        int pto = puerto;
        System.out.println("conectando con el servidor...");
        socket = new Socket(ipServidor, pto);
        Scanner entrada = new Scanner(socket.getInputStream());
        PrintStream salidaServer = new PrintStream(socket.getOutputStream());
        salidaServer.println(dato);
        clave = entrada.nextLine();
        System.out.println("Dato recibido: " + clave);
        socket.close();

    } catch (IOException ex) {
        System.err.println("Cliente> " + ex.getMessage());
    }
    return clave;
}

From source file:hudson.plugins.chainreactorclient.ChainReactorInvalidServerException.java

public boolean connect(ChainReactorServer server) {
    try {/* w  w w.  j  a v a 2  s  . c o  m*/
        InetSocketAddress sockaddr = server.getSocketAddress();
        Socket sock = new Socket();
        sock.setSoTimeout(2000);
        sock.connect(sockaddr, 2000);
        BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
        ensureValidServer(rd);
        logger.println("Connected to chain reactor server");
        sendBuildInfo(wr);
        rd.close();
        wr.close();
        sock.close();
    } catch (UnknownHostException uhe) {
        logError("Failed to resolve host: " + server.getUrl());
    } catch (SocketTimeoutException ste) {
        logError("Time out while trying to connect to " + server.toString());
    } catch (IOException ioe) {
        logError(ioe.getMessage());
    } catch (ChainReactorInvalidServerException crise) {
        logError(crise.getMessage());
    }

    return true;
}

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

public Request create(long acceptedOn, Socket s) throws CommunicationException, UnhandledException {
    boolean exception = false;
    try {//w w w  .j  a v  a 2  s .c  om
        HttpServerConnection connection = HttpServlet.bindSocketForHttp(s);
        Request request = create(connection);
        return request;
    } catch (CommunicationException e) {
        exception = true;
        throw e;
    } catch (Throwable t) {
        exception = true;
        throw new UnhandledException(t);
    } finally {
        if (exception) {
            try {
                s.close();
            } catch (IOException e) {
                // Do not even bother to log.
            }
        }
    }
}

From source file:InterruptibleSocketTest.java

/**
 * Connects to the test server, using blocking I/O
 *//*from w w  w.j a v  a2  s  .  c o m*/
public void connectBlocking() throws IOException {
    messages.append("Blocking:\n");
    Socket sock = new Socket("localhost", 8189);
    try {
        in = new Scanner(sock.getInputStream());
        while (!Thread.currentThread().isInterrupted()) {
            messages.append("Reading ");
            if (in.hasNextLine()) {
                String line = in.nextLine();
                messages.append(line);
                messages.append("\n");
            }
        }
    } finally {
        sock.close();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                messages.append("Socket closed\n");
                interruptibleButton.setEnabled(true);
                blockingButton.setEnabled(true);
            }
        });
    }
}

From source file:com.github.stephanarts.cas.ticket.registry.support.JSONRPCServerTest.java

@Test
public void testInvalidZMQ() throws Exception {
    JSONRPCServer s = new JSONRPCServer("tcp://localhost:7901");
    s.start();/*w  w w .  j  ava  2s . c  om*/

    java.net.Socket c = new java.net.Socket("localhost", 7901);
    java.io.PrintWriter out = new java.io.PrintWriter(c.getOutputStream(), true);
    out.print("BREAK_ZEROMQ");
    out.flush();
    c.close();

    s.cleanup();
}

From source file:SimpleHttpServerDataProvider.java

public SimpleHttpServer(SimpleHttpServerDataProvider dataProvider, int port) {

    class SocketProcessor implements Runnable {
        private Socket s;
        private InputStream is;
        private OutputStream os;
        private SimpleHttpServerDataProvider dataProvider;

        private SocketProcessor(Socket s, SimpleHttpServerDataProvider prov) throws Throwable {
            this.dataProvider = prov;
            this.s = s;
            this.is = s.getInputStream();
            this.os = s.getOutputStream();
        }/*from   w  ww .ja  v  a2s. c o  m*/

        public void run() {
            try {
                readInputHeaders();
                writeResponse("");
            } catch (Throwable t) {
                /*do nothing*/
            } finally {
                try {
                    s.close();
                } catch (Throwable t) {
                    /*do nothing*/
                }
            }

        }

        private void writeResponse(String s) throws Throwable {
            String response = "HTTP/1.1 200 OK\r\n" + "Server: DJudge.http\r\n" + "Content-Type: text/html\r\n"
                    + "Content-Length: " + s.length() + "\r\n" + "Connection: close\r\n\r\n";
            String result = response + dataProvider.getHtmlPage("");
            os.write(result.getBytes());
            os.flush();
        }

        private void readInputHeaders() throws Throwable {
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            while (true) {
                String s = br.readLine();
                if (s == null || s.trim().length() == 0) {
                    break;
                }

            }
        }
    }

    this.dataProvider = dataProvider;
    try {
        ServerSocket ss = new ServerSocket(port);

        while (true) {
            Socket s = ss.accept();

            new Thread(new SocketProcessor(s, dataProvider)).start();
        }
    } catch (Exception e) {

    } catch (Throwable e) {

    }
}