Example usage for java.net Socket Socket

List of usage examples for java.net Socket Socket

Introduction

In this page you can find the example usage for java.net Socket Socket.

Prototype

public Socket() 

Source Link

Document

Creates an unconnected Socket.

Usage

From source file:hudson.gridmaven.gridlayer.PluginImpl.java

/**
 * Compute the host name that Hadoop nodes can be used to talk to Name node.
 *
 * <p>// ww  w. j a v a  2s .co  m
 * We prefer to use {@link Hudson#getRootUrl()}, except we have to watch out for a possibility
 * that it points to a front end (like apache, router with port-forwarding, etc.), and if that is the case,
 * use some heuristics to find out a usable host name.
 *
 * TODO: move this to {@code Hudson.toComputer().getHostName()}. 
 */
String getMasterHostName() throws IOException, InterruptedException {
    // check if rootURL is reliable
    Hudson h = Hudson.getInstance();
    String rootUrl = h.getRootUrl();
    if (rootUrl == null) {
        // the only option is to auto-detect.
        String real = h.toComputer().getHostName();
        LOGGER.fine("Hudson root URL isn't configured. Using " + real + " instead");
        return real;
    }

    // according to Hudson's setting, this is the host name that we can use to connect to master,
    // at least for HTTP. See if we can connect to the arbitrary port in this way.
    final String hostName = new URL(rootUrl).getHost();
    final ServerSocket ss = new ServerSocket(0);

    Thread t = new Thread() {
        @Override
        public void run() {
            try {
                ss.accept();
            } catch (IOException e) {
                // shouldn't happen
                LOGGER.log(Level.INFO, "Failed to accept", e);
            } finally {
                try {
                    ss.close();
                } catch (IOException e) {
                    // ignore
                }
            }
        }
    };
    t.start();

    try {
        Socket s = new Socket();
        s.connect(new InetSocketAddress(hostName, ss.getLocalPort()), 1000);
        s.close();

        // yep, it worked
        return hostName;
    } catch (IOException e) {
        // no it didn't
        String real = h.toComputer().getHostName();
        LOGGER.fine("Hudson root URL " + rootUrl + " looks like a front end. Using " + real + " instead");
        return real;
    }
}

From source file:com.cloudant.tests.CloudantClientTests.java

/**
 * Check that the connection timeout throws a SocketTimeoutException when it can't connect
 * within the timeout.//w w w  .  java  2s.  c om
 */
@Test(expected = SocketTimeoutException.class)
public void connectionTimeout() throws Throwable {

    ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(0, 1);

    //block the single connection to our server
    Socket socket = new Socket();
    socket.connect(serverSocket.getLocalSocketAddress());

    //now try to connect, but should timeout because there is no connection available
    try {
        CloudantClient c = ClientBuilder.url(new URL("http://127.0.0.1:" + serverSocket.getLocalPort()))
                .connectTimeout(100, TimeUnit.MILLISECONDS).build();

        // Make a request
        c.getAllDbs();
    } catch (CouchDbException e) {
        //unwrap the CouchDbException
        if (e.getCause() != null) {
            //whilst it would be really nice to actually assert that this was a connect
            //exception and not some other SocketTimeoutException there are JVM differences in
            //this respect (i.e. OpenJDK does not appear to distinguish between read/connect)
            //in its exception messages
            throw e.getCause();
        } else {
            throw e;
        }
    } finally {
        //make sure we close the sockets
        IOUtils.closeQuietly(serverSocket);
        IOUtils.closeQuietly(socket);
    }
}

From source file:com.linecorp.armeria.server.ServerTest.java

@Test(timeout = idleTimeoutMillis * 5)
public void testIdleTimeoutByNoContentSent() throws Exception {
    try (Socket socket = new Socket()) {
        socket.setSoTimeout((int) (idleTimeoutMillis * 4));
        socket.connect(server().activePort().get().localAddress());
        long connectedNanos = System.nanoTime();
        //read until EOF
        while (socket.getInputStream().read() != -1) {
            continue;
        }//  w  w w .j  a v  a  2s  . c om
        long elapsedTimeMillis = TimeUnit.MILLISECONDS.convert(System.nanoTime() - connectedNanos,
                TimeUnit.NANOSECONDS);
        assertThat(elapsedTimeMillis, is(greaterThanOrEqualTo(idleTimeoutMillis)));
    }
}

From source file:com.serotonin.modbus4j.ip.tcp.TcpMaster.java

private void openConnection() throws IOException {
    // Make sure any existing connection is closed.
    closeConnection();// w  w  w. j ava2 s .  c  o m

    // Try 'retries' times to get the socket open.
    int retries = getRetries();
    int retryPause = RETRY_PAUSE_START;
    while (true) {
        try {
            socket = new Socket();
            socket.setSoTimeout(getTimeout());
            socket.connect(new InetSocketAddress(ipParameters.getHost(), ipParameters.getPort()), getTimeout());
            if (getePoll() != null)
                transport = new EpollStreamTransport(socket.getInputStream(), socket.getOutputStream(),
                        getePoll());
            else
                transport = new StreamTransport(socket.getInputStream(), socket.getOutputStream());
            break;
        } catch (IOException e) {
            closeConnection();

            if (retries <= 0)
                throw e;
            // System.out.println("Modbus4J: Open connection failed, trying again.");
            retries--;

            // Pause for a bit.
            try {
                Thread.sleep(retryPause);
            } catch (InterruptedException e1) {
                // ignore
            }
            retryPause *= 2;
            if (retryPause > RETRY_PAUSE_MAX)
                retryPause = RETRY_PAUSE_MAX;
        }
    }

    BaseMessageParser ipMessageParser;
    WaitingRoomKeyFactory waitingRoomKeyFactory;
    if (ipParameters.isEncapsulated()) {
        ipMessageParser = new EncapMessageParser(true);
        waitingRoomKeyFactory = new EncapWaitingRoomKeyFactory();
    } else {
        ipMessageParser = new XaMessageParser(true);
        waitingRoomKeyFactory = new XaWaitingRoomKeyFactory();
    }

    conn = getMessageControl();
    conn.start(transport, ipMessageParser, null, waitingRoomKeyFactory);
    if (getePoll() == null)
        ((StreamTransport) transport).start("Modbus4J TcpMaster");
}

From source file:totalcross.android.ConnectionManager4A.java

public static boolean isInternetAccessible() {
    try {// w w  w .  j  a  v a  2s. co  m
        InetSocketAddress isa = new InetSocketAddress(InetAddress.getByName("www.google.com"), 80);
        Socket s = new Socket();
        s.connect(isa, 30 * 1000);
        s.close();
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:hudson.cli.CLI.java

/**
 * @deprecated Specific to {@link Mode#REMOTING}.
 *//*from  w  ww. j  a  v  a 2 s  .co m*/
@Deprecated
private Channel connectViaCliPort(URL jenkins, CliPort clip) throws IOException {
    LOGGER.log(FINE, "Trying to connect directly via Remoting over TCP/IP to {0}", clip.endpoint);

    if (authorization != null) {
        LOGGER.warning("-auth ignored when using JNLP agent port");
    }

    final Socket s = new Socket();
    // this prevents a connection from silently terminated by the router in between or the other peer
    // and that goes without unnoticed. However, the time out is often very long (for example 2 hours
    // by default in Linux) that this alone is enough to prevent that.
    s.setKeepAlive(true);
    // we take care of buffering on our own
    s.setTcpNoDelay(true);
    OutputStream out;

    if (httpsProxyTunnel != null) {
        String[] tokens = httpsProxyTunnel.split(":");
        LOGGER.log(Level.FINE, "Using HTTP proxy {0}:{1} to connect to CLI port",
                new Object[] { tokens[0], tokens[1] });
        s.connect(new InetSocketAddress(tokens[0], Integer.parseInt(tokens[1])));
        PrintStream o = new PrintStream(s.getOutputStream());
        o.print("CONNECT " + clip.endpoint.getHostString() + ":" + clip.endpoint.getPort()
                + " HTTP/1.0\r\n\r\n");

        // read the response from the proxy
        ByteArrayOutputStream rsp = new ByteArrayOutputStream();
        while (!rsp.toString("ISO-8859-1").endsWith("\r\n\r\n")) {
            int ch = s.getInputStream().read();
            if (ch < 0)
                throw new IOException("Failed to read the HTTP proxy response: " + rsp);
            rsp.write(ch);
        }
        String head = new BufferedReader(new StringReader(rsp.toString("ISO-8859-1"))).readLine();

        if (head == null) {
            throw new IOException("Unexpected empty response");
        }
        if (!(head.startsWith("HTTP/1.0 200 ") || head.startsWith("HTTP/1.1 200 "))) {
            s.close();
            LOGGER.log(Level.SEVERE,
                    "Failed to tunnel the CLI port through the HTTP proxy. Falling back to HTTP.");
            throw new IOException("Failed to establish a connection through HTTP proxy: " + rsp);
        }

        // HTTP proxies (at least the one I tried --- squid) doesn't seem to do half-close very well.
        // So instead of relying on it, we'll just send the close command and then let the server
        // cut their side, then close the socket after the join.
        out = new SocketOutputStream(s) {
            @Override
            public void close() throws IOException {
                // ignore
            }
        };
    } else {
        s.connect(clip.endpoint, 3000);
        out = SocketChannelStream.out(s);
    }

    closables.add(new Closeable() {
        public void close() throws IOException {
            s.close();
        }
    });

    Connection c = new Connection(SocketChannelStream.in(s), out);

    switch (clip.version) {
    case 1:
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        dos.writeUTF("Protocol:CLI-connect");
        // we aren't checking greeting from the server here because I'm too lazy. It gets ignored by Channel constructor.
        break;
    case 2:
        DataInputStream dis = new DataInputStream(s.getInputStream());
        dos = new DataOutputStream(s.getOutputStream());
        dos.writeUTF("Protocol:CLI2-connect");
        String greeting = dis.readUTF();
        if (!greeting.equals("Welcome"))
            throw new IOException("Handshaking failed: " + greeting);
        try {
            byte[] secret = c.diffieHellman(false).generateSecret();
            SecretKey sessionKey = new SecretKeySpec(Connection.fold(secret, 128 / 8), "AES");
            c = c.encryptConnection(sessionKey, "AES/CFB8/NoPadding");

            // validate the instance identity, so that we can be sure that we are talking to the same server
            // and there's no one in the middle.
            byte[] signature = c.readByteArray();

            if (clip.identity != null) {
                Signature verifier = Signature.getInstance("SHA1withRSA");
                verifier.initVerify(clip.getIdentity());
                verifier.update(secret);
                if (!verifier.verify(signature))
                    throw new IOException("Server identity signature validation failed.");
            }

        } catch (GeneralSecurityException e) {
            throw (IOException) new IOException("Failed to negotiate transport security").initCause(e);
        }
    }

    return new Channel("CLI connection to " + jenkins, pool, new BufferedInputStream(c.in),
            new BufferedOutputStream(c.out));
}

From source file:com.carreygroup.JARVIS.Demon.java

/******************************TCP
 * @throws UnknownHostException ******************************/
public boolean Connection(byte mode, String argv1, String argv2) throws UnknownHostException {
    Ethnet_Mode = mode;/* w  w w .j av  a  2s  . co m*/
    if (Ethnet_Mode == Ethnet.P2P) {
        P2PConnect(argv1, argv2);

    } else if (Ethnet_Mode == Ethnet.TCP) {
        //,IP
        java.net.InetAddress x;
        x = java.net.InetAddress.getByName(argv1);
        String host = x.getHostAddress();//ip      

        int port = Integer.valueOf(argv2);
        try {
            mSocket = new Socket();
            mAddress = new InetSocketAddress(host, port);
            mSocket.connect(mAddress, 5000);
            mPrintWriterClient = new PrintWriter(mSocket.getOutputStream(), true);
            if (mSocket.isConnected())
                Log.v("_DEBUG", "Connected!");
            else
                Log.v("_DEBUG", "No Connected!");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //  
        // new Thread(new ActiveTest(mSocket.socket())).start();
    } else if (Ethnet_Mode == Ethnet.UDP) {
        //,IP
        java.net.InetAddress x;
        x = java.net.InetAddress.getByName(argv1);
        String host = x.getHostAddress();//ip      
        int port = Integer.valueOf(argv2);

        mAddress = new InetSocketAddress(host, port);
        try {
            mSendPSocket = new DatagramSocket();
            mSendPSocket.setBroadcast(true);
            mReceviedSocket = new DatagramSocket(port);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }

    if (Connected()) {
        for (ConnectionListener listener : mConnListeners) {
            listener.onConnected(this);
        }
    }
    return Connected();
}

From source file:SocketFetcher.java

/**
 * Create a socket with the given local address and connected to
 * the given host and port.  Use the specified connection timeout.
 * If a socket factory is specified, use it.  Otherwise, use the
 * SSLSocketFactory if useSSL is true./*  w ww . j a  v a  2 s.  co m*/
 */
private static Socket createSocket(InetAddress localaddr, int localport, String host, int port, int cto,
        SocketFactory sf, boolean useSSL) throws IOException {
    Socket socket;

    if (sf != null)
        socket = sf.createSocket();
    else if (useSSL)
        socket = SSLSocketFactory.getDefault().createSocket();
    else
        socket = new Socket();
    if (localaddr != null)
        socket.bind(new InetSocketAddress(localaddr, localport));
    if (cto >= 0)
        socket.connect(new InetSocketAddress(host, port), cto);
    else
        socket.connect(new InetSocketAddress(host, port));
    return socket;
}

From source file:ca.uhn.hunit.example.MllpHl7v2MessageSwapper.java

@Override
public void run() {
    Socket socket = null;// w  w w .  jav a  2  s  .c  o m

    try {
        if (myPrintOutput) {
            System.out.println("Opening server socket on port " + 10201);
        }

        ServerSocket serverSocket = new ServerSocket(10201);

        socket = serverSocket.accept();

        InputStream inputStream = socket.getInputStream();
        inputStream = new BufferedInputStream(inputStream);

        MinLLPReader minLLPReader = new MinLLPReader(inputStream);

        Socket outSocket = null;

        if (myPrintOutput) {
            System.out.println("Accepting connection from " + socket.getInetAddress().getHostAddress());
        }

        for (int i = 0; i < myIterations; i++) {
            String messageText;

            do {
                messageText = minLLPReader.getMessage();
                Thread.sleep(250);
            } while (messageText == null);

            if (myPrintOutput) {
                System.out.println("Received message:\r\n" + messageText + "\r\n");
            }

            MSH inboundHeader = (MSH) myParser.parse(messageText).get("MSH");
            String controlId = inboundHeader.getMessageControlID().encode();
            if (StringUtils.isNotBlank(controlId) && myControlIdsToIgnore.indexOf(controlId) > -1) {
                Message replyAck = DefaultApplication.makeACK(inboundHeader);
                new MinLLPWriter(socket.getOutputStream()).writeMessage(myParser.encode(replyAck));
            } else {
                System.out.println("Ignoring message with control ID " + controlId);
            }

            for (Map.Entry<String, String> next : mySubstitutions.entrySet()) {
                messageText = messageText.replace(next.getKey(), next.getValue());
            }

            if ((outSocket != null) && myAlwaysCreateNewOutboundConnection) {
                outSocket.close();
                outSocket = null;
            }

            if (outSocket == null) {
                if (myPrintOutput) {
                    System.out.println("Opening outbound connection to port " + 10200);
                }

                outSocket = new Socket();
                outSocket.connect(new InetSocketAddress("localhost", 10200));
            }

            if (myPrintOutput) {
                System.out.println("Sending message from port " + outSocket.getLocalPort() + ":\r\n"
                        + messageText + "\r\n");
            }

            new MinLLPWriter(outSocket.getOutputStream()).writeMessage(messageText);
            new MinLLPReader(outSocket.getInputStream()).getMessage();
        }

        serverSocket.close();
        socket.close();

        myStopped = true;

    } catch (Exception e) {
        myStopped = true;
        e.printStackTrace();
    }
}

From source file:it.anyplace.sync.discovery.utils.AddressRanker.java

private int doTestTcpConnection(SocketAddress socketAddress) {
    logger.debug("test tcp connection to address = {}", socketAddress);
    Stopwatch stopwatch = Stopwatch.createStarted();
    try (Socket socket = new Socket()) {
        socket.setSoTimeout(TCP_CONNECTION_TIMEOUT);
        socket.connect(socketAddress, TCP_CONNECTION_TIMEOUT);
    } catch (IOException ex) {
        logger.debug("address unreacheable = {} ({})", socketAddress, ex.toString());
        logger.trace("address unreacheable", ex);
        return -1;
    }/*from   w  ww . ja v  a2 s. co m*/
    int time = (int) stopwatch.elapsed(TimeUnit.MILLISECONDS);
    logger.debug("tcp connection to address = {} is ok, time = {} ms", socketAddress, time);
    return time;
}