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.linuxbox.enkive.importer.AbstractMessageImporter.java

protected void setWriter() throws IOException {
    socket = new Socket(host, port);
    socket.setSendBufferSize(8);// ww w .  j  av  a2 s .c  o m
    writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
}

From source file:pl.edu.agh.ServiceConnection.java

/**
 * 1. Sends data to service: console password | service password | service id
 *//*from w w  w.  ja  v  a2s . com*/
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:com.navercorp.pinpoint.profiler.sender.TcpDataSender.java

public TcpDataSender(PinpointClient client, String collectorTcpServerIp, int port) {
    this.client = client;
    this.timer = createTimer();
    writeFailFutureListener = new WriteFailFutureListener(logger, "io write fail.", "host", -1);
    this.executor = createAsyncQueueingExecutor(1024 * 5, "Pinpoint-TcpDataExecutor");
    try {/*from   w w w .j av  a  2 s .  co m*/
        socket = new Socket(collectorTcpServerIp, port);
        ops = socket.getOutputStream();
    } catch (IOException e) {
        logger.error("create socket failed", e);
    }
}

From source file:ezbake.thriftrunner.starters.SimpleStarter.java

boolean clientSideSocketIsFree(int port) {
    Socket clientSocket = null;/*from   w w w. j  a  v a 2  s. c  o m*/
    try {
        clientSocket = new Socket(hostName, port);
    } catch (final IOException e) {
        return true;
    } finally {
        if (clientSocket != null) {
            try {
                clientSocket.close();
            } catch (final IOException e) {
                // Should never happen
            }
        }
    }
    return false;
}

From source file:com.kyne.webby.rtk.modules.BukkitInterface.java

@SuppressWarnings("unchecked")
private <T> T sendRequestAndCastResponse(final RequestType type, final Map<String, Object> params,
        final Class<T> responseDataType) throws IOException {
    Socket clientSocket = null;//w  ww. j ava 2 s . c om
    ObjectOutputStream serverOutputStream = null;
    ObjectInputStream serverInputStream = null;

    final WebbyLocalData request = new WebbyLocalData(type, params);
    try {
        clientSocket = new Socket("localhost", this.localPort);
        serverOutputStream = new ObjectOutputStream(clientSocket.getOutputStream());
        serverInputStream = new ObjectInputStream(clientSocket.getInputStream());
        serverOutputStream.writeObject(request);
        final WebbyLocalData response = (WebbyLocalData) serverInputStream.readObject();
        if (this.lastKnownStatus != ServerStatus.RESTARTING) {
            this.lastKnownStatus = ServerStatus.ON;
        }
        return (T) response.getRequestParams().get("DATA");
    } catch (final Exception e) {
        this.lastKnownStatus = ServerStatus.OFF;
        LogHelper.debug("Bukkit is offline or restarting");
        return null;
    } finally {
        IOUtils.closeQuietly(serverInputStream);
        IOUtils.closeQuietly(serverOutputStream);
        IOUtils.closeQuietly(clientSocket);
    }
}

From source file:org.mariotaku.twidere.util.net.HostResolvedSocketFactory.java

@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
    final String hostName = host.getHostName();
    final String resolvedHost = resolver.resolve(hostName);
    if (resolvedHost != null && !resolvedHost.equals(hostName)) {
        if (InetAddressUtils.isIPv6Address(resolvedHost)) {
            final byte[] resolvedAddress = Inet6Address.getByName(resolvedHost).getAddress();
            return new Socket(InetAddress.getByAddress(hostName, resolvedAddress), port);
        } else if (InetAddressUtils.isIPv4Address(resolvedHost)) {
            final byte[] resolvedAddress = Inet4Address.getByName(resolvedHost).getAddress();
            return new Socket(InetAddress.getByAddress(hostName, resolvedAddress), port);
        }//w w w.ja  v  a 2 s  .  c  om
    }
    return defaultFactory.createSocket(host, port);
}

From source file:org.signserver.client.cli.performance.PerformanceTestPDFServlet.java

License:asdf

/** @see org.signserver.client.PerformanceTestTask */
public boolean invoke(int threadId) {
    if (startTime == 0) {
        startTime = System.currentTimeMillis();
    }/* w ww. j a v  a2 s .  c  o  m*/
    byte[] testPDF = pdfs
            .get((int) ((System.currentTimeMillis() - startTime) * ((long) pdfs.size()) / runTime));
    URL target;
    try {
        target = new URL(baseURLString);
        InetAddress addr = InetAddress.getByName(target.getHost());
        Socket socket = new Socket(addr, target.getPort());
        OutputStream raw = socket.getOutputStream();
        final int contentLength = REQUEST_CONTENT_WORKERNAME.length() + REQUEST_CONTENT_FILE.length()
                + testPDF.length + REQUEST_CONTENT_END.length();
        final String command = "POST " + target.getPath() + "pdf HTTP/1.0\r\n"
                + "Content-Type: multipart/form-data; boundary=signserver\r\n" + "Content-Length: "
                + contentLength + "\r\n" + "\r\n";
        raw.write(command.getBytes());
        raw.write(REQUEST_CONTENT_WORKERNAME.getBytes());
        raw.write(REQUEST_CONTENT_FILE.getBytes());
        raw.write(testPDF);
        raw.write(REQUEST_CONTENT_END.getBytes());
        raw.flush();

        InputStream in = socket.getInputStream();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf)) > 0) {
            os.write(buf, 0, len);
        }
        in.close();
        os.close();
        byte[] inbytes = os.toByteArray();

        PdfReader pdfReader = new PdfReader(inbytes);
        if (!new String(pdfReader.getPageContent(1)).contains(PDF_CONTENT)) {
            System.err.println("Did not get the same document back..");
            return false;
        }
        pdfReader.close();
        raw.close();
        socket.close();
    } catch (IOException e) {
        System.err.println("testPDF.length=" + testPDF.length + "," + e.getMessage());
        //e.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.inmobi.messaging.util.GraphiteStatsEmitter.java

protected void writeStats() {
    if (null != statsExposers) {
        synchronized (statsExposers) {
            final StringBuilder lines = new StringBuilder();
            long timestamp = System.currentTimeMillis() / 1000;
            for (StatsExposer exposer : statsExposers) {
                Map<String, Number> stats = exposer.getStats();
                Map<String, String> context = exposer.getContexts();
                String topic = context.get(TopicStatsExposer.TOPIC_CONTEXT_NAME);
                /**/*  w w  w .  j  av a  2  s. c  o m*/
                 * Publisher will be having topic set as category in the statsexposer,
                 * but for consumers topic is set as topicName for the statsexposer.
                 */
                if (null == topic) {
                    topic = context.get(MessageConsumerMetricsConstants.TOPIC_CONTEXT);
                }
                for (Map.Entry<String, Number> entry : stats.entrySet()) {
                    lines.append(metricPrefix).append(topic).append(METRIC_SEPARATOR).append(entry.getKey());
                    lines.append(FIELD_SEPARATOR);
                    lines.append(entry.getValue().longValue());
                    lines.append(FIELD_SEPARATOR);
                    lines.append(timestamp);
                    lines.append(NEW_LINE);
                }
            }

            Socket graphiteSocket = null;
            OutputStream stream = null;
            try {
                graphiteSocket = new Socket(graphiteHost, graphitePort);
                stream = graphiteSocket.getOutputStream();
                stream.write(lines.toString().getBytes(Charset.forName("UTF-8")));
            } catch (IOException ex) {
                LOG.error("Failed to write the stats", ex);
            } finally {
                if (null != graphiteSocket && !graphiteSocket.isClosed()) {
                    try {
                        graphiteSocket.close();
                    } catch (IOException ex) {
                        LOG.warn("failure in closing the connection to graphite server", ex);
                    }
                }
                if (null != stream) {
                    try {
                        stream.close();
                    } catch (IOException ex) {
                        LOG.warn("failure in closing the input stream", ex);
                    }
                }
            }
        }
    }
}

From source file:org.apache.hyracks.http.test.HttpServerTest.java

@Test
public void testMalformedString() throws Exception {
    WebManager webMgr = new WebManager();
    HttpServer server = new HttpServer(webMgr.getBosses(), webMgr.getWorkers(), PORT, NUM_EXECUTOR_THREADS,
            SERVER_QUEUE_SIZE);/*from  ww  w.java 2  s  .  c o m*/
    SlowServlet servlet = new SlowServlet(server.ctx(), new String[] { PATH });
    server.addServlet(servlet);
    webMgr.add(server);
    webMgr.start();
    try {
        StringBuilder response = new StringBuilder();
        try (Socket s = new Socket(InetAddress.getLocalHost(), PORT)) {
            PrintWriter pw = new PrintWriter(s.getOutputStream());
            pw.println("GET /?handle=%7B%22handle%22%3A%5B0%2C%200%5D%7 HTTP/1.1");
            pw.println("Host: 127.0.0.1");
            pw.println();
            pw.flush();
            BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line).append('\n');
            }
            br.close();
        }
        String output = response.toString();
        Assert.assertTrue(output.contains(HttpResponseStatus.BAD_REQUEST.toString()));
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        webMgr.stop();
    }
}

From source file:com.alibaba.jstorm.yarn.utils.JstormYarnUtils.java

/**
 * See if a port is available for listening on by trying connect to it
 * and seeing if that works or fails//from www.j a  v a 2s .  c  om
 *
 * @param host
 * @param port
 * @return
 */
public static boolean isPortAvailable(String host, int port) {
    try {
        Socket socket = new Socket(host, port);
        socket.close();
        return false;
    } catch (IOException e) {
        return true;
    }
}