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(InetAddress address, int port) throws IOException 

Source Link

Document

Creates a stream socket and connects it to the specified port number at the specified IP address.

Usage

From source file:com.fluffypeople.managesieve.ManageSieveClient.java

/**
 * Connect to remote server//  www . ja v  a 2s.  co  m
 *
 * @return ManageSieveResponse OK on connect, NO on connection problems
 * @throws IOException if there are underlying IO issues
 * @throws ParseException if we can't parse the response from the server
 */
public synchronized ManageSieveResponse connect(final String host, final int port)
        throws IOException, ParseException {
    hostname = host;
    socket = new Socket(InetAddress.getByName(hostname), port);

    setupAfterConnect(socket);
    return parseCapabilities();
}

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 w w  .j  ava  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(host, port);
    else if (useSSL)
        socket = SSLSocketFactory.getDefault().createSocket(host, port);
    else
        socket = new Socket(host, port);
    /*
     * if (localaddr != null) socket.bind(new InetAddress(localaddr,
     * localport)); if (cto >= 0) socket.connect(new InetSocketAddress(host,
     * port), cto); else socket.connect(new InetSocketAddress(host, port));
     */
    return socket;
}

From source file:com.moss.appsnap.keeper.windows.MSWindowsDesktopIntegrationStrategy.java

@Override
public ApiMessageConnection newMessageToHost() {
    try {//from www.  j a v  a  2  s . c om
        Socket s = new Socket("127.0.0.1", KEEPER_LOCAL_PORT);
        return new SocketMessageConnection(s);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.commons.httpclient.contrib.ssl.StrictSSLProtocolSocketFactory.java

/**
 * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)
 *//* w  w  w .  j  av  a2s .c  o  m*/
public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)
        throws IOException, UnknownHostException {
    SSLSocketFactory sf = SSLSocketFactory.getSocketFactory();
    SSLSocket sslSocket = (SSLSocket) sf.createSocket(new Socket(host, port), clientHost.toString(), clientPort,
            true);
    verifyHostname(sslSocket);

    return sslSocket;
}

From source file:cnxchecker.Client.java

private void doit() {
    // Check we can connect to the server
    try {/* ww w.  ja  v a 2 s  . c om*/
        Socket s = new Socket(this.ia, this.port);
        s.close();
    } catch (IOException e) {
        printAndExit("Failed to contact " + this.ia + " " + this.port);
    }

    // Start the workers
    for (int i = 0; i < this.workers.length; i++) {
        try {
            workers[i] = new Worker(i);
            workers[i].start();
        } catch (Exception e) {
            System.out.println("[ERROR] worker#" + i + ": failed to start thread -> " + e.getMessage());
            System.exit(1);
        }
    }

    try {
        Thread.sleep(this.duration);
    } catch (InterruptedException e) {
        // Ok
    }

    for (int i = 0; i < this.workers.length; i++) {
        workers[i].terminate();
    }

    System.out.println("Exiting");
}

From source file:bpv.neurosky.connector.ThinkGearSocket.java

public void start() throws ConnectException {

    try {/*  ww w .  j  av a 2  s . c  om*/
        neuroSocket = new Socket("127.0.0.1", 13854);
    } catch (ConnectException e) {
        //e.printStackTrace();
        System.out.println("Oi plonker! Is ThinkkGear running?");
        running = false;
        throw e;
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        inStream = neuroSocket.getInputStream();
        outStream = neuroSocket.getOutputStream();
        stdIn = new BufferedReader(new InputStreamReader(neuroSocket.getInputStream()));
        running = true;
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (appName != "" && appKey != "") {
        JSONObject appAuth = new JSONObject();
        try {
            appAuth.put("appName", appName);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            appAuth.put("appKey", appKey);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        //throws some error
        sendMessage(appAuth.toString());
        System.out.println("appAuth" + appAuth);
    }

    JSONObject format = new JSONObject();
    try {
        format.put("enableRawOutput", true);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        System.out.println("raw error");
        e.printStackTrace();
    }
    try {
        format.put("format", "Json");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        System.out.println("Json error");
        e.printStackTrace();
    }
    //System.out.println("format "+format);
    sendMessage(format.toString());
    t = new Thread(this);
    t.start();
    System.out.println("Conexo Estabelecida: Iniciando leitura de socket...");

}

From source file:com.nirima.jenkins.SimpleArtifactCopier.java

protected List<String> fetchFiles(Artifact art)
        throws IOException, URISyntaxException, UnsupportedEncodingException, UnknownHostException,
        HttpException, TransformerException, SAXException, ParserConfigurationException {

    List<String> entries = null;

    URL url = new URL(host,
            art.getGroupId().replace('.', '/') + "/" + art.getArtifactId() + "/" + art.getVersion() + "/");

    //url = new URL(url, "LastSuccessful/repository");
    BasicHttpEntityEnclosingRequest httpget = new BasicHttpEntityEnclosingRequest("PROPFIND",
            url.toURI().getPath());// w ww.java2  s .c  om
    //System.out.println("url=" + url);
    // HEADER
    String s = "<propget><allprop/></propget>";
    StringEntity se = new StringEntity(s, "US-ASCII");
    se.setChunked(false);
    httpget.setEntity(se);

    // Start

    if (!conn.isOpen()) {
        Socket socket = new Socket(targetHost.getHostName(),
                targetHost.getPort() > 0 ? targetHost.getPort() : 80);
        conn.bind(socket, params);
    }

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);

    httpexecutor.preProcess(httpget, httpproc, context);
    HttpResponse response = httpexecutor.execute(httpget, conn, context);
    httpexecutor.postProcess(response, httpproc, context);

    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        try {

            if (instream != null) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                IOUtils.copy(instream, baos);

                entries = getEntries(baos.toByteArray());
            }

        } catch (IOException ex) {
            conn.shutdown();

        } finally {
            instream.close();
        }
    }
    if (!connStrategy.keepAlive(response, context)) {
        conn.close();
    }

    // End

    return entries;
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.google.GoogleProviderUtils.java

static private boolean checkIfProxyIsOpen(Proxy proxy) {
    boolean connected = false;
    int tries = 0;
    int port = proxy.getPort();

    while (!connected && tries < connectRetries) {
        tries++;/*from w  ww.j  av  a  2  s  .  c o m*/

        try {
            log.info("Attempting to connect to localhost:" + port + "...");
            Socket testSocket = new Socket("localhost", port);
            log.info("Connection opened");

            connected = testSocket.isConnected();
            testSocket.close();
        } catch (IOException e) {
            DaemonTaskHandler.safeSleep(TimeUnit.SECONDS.toMillis(5));
        }
    }

    return connected;
}

From source file:com.boozallen.cognition.kom.KafakOffsetMonitor.java

private void sendToLogstash(Map<TopicAndPartition, Long> kafkaSpoutOffsets,
        Map<TopicAndPartition, SimpleConsumer> kafkaConsumers) throws IOException {
    for (TopicAndPartition topicAndPartition : kafkaConsumers.keySet()) {
        Map<TopicAndPartition, PartitionOffsetRequestInfo> requestMap = new HashMap<>();
        requestMap.put(topicAndPartition,
                PartitionOffsetRequestInfo.apply(kafka.api.OffsetRequest.LatestTime(), 1));
        OffsetRequest offsetRequest = new OffsetRequest(requestMap, kafka.api.OffsetRequest.CurrentVersion(),
                kafka.api.OffsetRequest.DefaultClientId());

        SimpleConsumer consumer = kafkaConsumers.get(topicAndPartition);
        OffsetResponse offsetResponse = consumer.getOffsetsBefore(offsetRequest);
        if (offsetResponse.hasError()) {
            System.out.println("error");
        } else {/*from w  ww. jav a  2 s  .  com*/
            String topic = topicAndPartition.topic();
            int partition = topicAndPartition.partition();
            long head = offsetResponse.offsets(topic, partition)[0];
            long kafkaSpoutOffset = kafkaSpoutOffsets.get(topicAndPartition);

            XContentBuilder builder = jsonBuilder().startObject().field("topic", topic)
                    .field("partition", partition).field("kafkaSpoutOffset", kafkaSpoutOffset)
                    .field("head", head).field("gap", head - kafkaSpoutOffset)
                    .field("application", "kafkaSpout").endObject();
            String json = builder.string();

            try (Socket socket = new Socket(logstashHost, logstashPort)) {
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                out.println(json);
            }
        }
    }
}

From source file:com.impetus.client.cassandra.common.CassandraUtilities.java

/**
* 
* @param host//from w w  w . j  a  va 2  s  . co m
* @param port
* @return
*/
public static boolean verifyConnection(String host, int port) {
    Socket socket = null;
    try {
        socket = new Socket(host, port);
        socket.setReuseAddress(true);
        socket.setSoLinger(true, 0);
        boolean isConnected = socket.isConnected();
        return isConnected;
    } catch (UnknownHostException e) {
        logger.warn("{}:{} is still down", host, port);
        return false;
    } catch (IOException e) {
        logger.warn("{}:{} is still down", host, port);
        return false;
    } finally {
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            logger.warn("{}:{} is still down", host, port);
        }
    }
}