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:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java

/**
 * Test robustness.// w w w .j  av a  2 s.com
 * 
 * @throws Exception
 *             When the test failed.
 */
@Test
public void testMissingOpen() throws Exception {
    final Agent agent = new org.kjkoster.zapcat.zabbix.ZabbixAgent();
    // give the agent some time to open the port
    Thread.sleep(100);
    final Socket socket = new Socket(InetAddress.getLocalHost(),
            org.kjkoster.zapcat.zabbix.ZabbixAgent.DEFAULT_PORT);

    final Writer out = new OutputStreamWriter(socket.getOutputStream());
    out.write("jmx(foo]\n");
    out.flush();

    final InputStream in = socket.getInputStream();
    final byte[] buffer = new byte[1024];
    final int read = in.read(buffer);
    assertEquals(29, read);

    assertEquals('Z', buffer[0]);
    assertEquals('B', buffer[1]);
    assertEquals('X', buffer[2]);
    assertEquals('D', buffer[3]);

    assertEquals('N', buffer[17]);
    assertEquals('O', buffer[18]);
    assertEquals('T', buffer[19]);

    // we'll take the rest for granted...

    socket.close();
    agent.stop();
}

From source file:hudson.TcpSlaveAgentListener.java

/**
 * Initiates the shuts down of the listener.
 *///from   w  ww  .  jav  a  2 s .c  o m
public void shutdown() {
    shuttingDown = true;
    try {
        SocketAddress localAddress = serverSocket.getLocalAddress();
        if (localAddress instanceof InetSocketAddress) {
            InetSocketAddress address = (InetSocketAddress) localAddress;
            Socket client = new Socket(address.getHostName(), address.getPort());
            client.setSoTimeout(1000); // waking the acceptor loop should be quick
            new PingAgentProtocol().connect(client);
        }
    } catch (IOException e) {
        LOGGER.log(Level.FINE, "Failed to send Ping to wake acceptor loop", e);
    }
    try {
        serverSocket.close();
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, "Failed to close down TCP port", e);
    }
}

From source file:br.gov.frameworkdemoiselle.monitoring.internal.implementation.zabbix.ZabbixSender.java

/**
 * Retrieves all active checks configured in the server.
 * /* www.j  av a2  s .c  om*/
 * @param hostname
 * @return   List<ActiveCheck>
 * @throws IOException
 */
public List<ActiveCheck> getActiveChecks(String hostname) throws IOException {

    List<ActiveCheck> list = new ArrayList<ActiveCheck>();

    Socket socket = null;
    OutputStream out = null;
    BufferedReader brin = null;

    try {
        socket = new Socket(zabbixServer, zabbixPort);
        socket.setSoTimeout(TIMEOUT);

        out = socket.getOutputStream();
        brin = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        // send request to Zabbix server and wait for the list of items to be returned
        out.write(createGetActiveChecksRequest(hostname));

        while (!socket.isClosed()) {
            String line = brin.readLine();

            if (line == null)
                break;

            // all active checks received
            if (line.startsWith(ZBX_EOF))
                break;

            list.add(parseActiveCheck(hostname, line));
        }

    } finally {
        if (brin != null) {
            brin.close();
        }
        if (out != null) {
            out.close();
        }
        if (socket != null) {
            socket.close();
        }
    }

    return list;
}

From source file:com.clough.android.adbv.manager.ADBManager.java

/**
 * Waiting for a device to connect and connect with it's one of eligible 
 * android application for AndroidDBViewer to run.
 * @return IOManager instance configured for a android application
 * @throws IOException/* w  w w.j a  v a2s  . co m*/
 * @throws ADBManagerException 
 */
public IOManager makeConnection() throws IOException, ADBManagerException {

    // Placing adb executable files for the desktop application use
    placeRelevantAdb();

    // Trying to connect with android application again and agian 
    // when ever an attempt is fail
    while (true) {
        try {

            // Creating a socket with PC_PORT and trying to connect with an server socket.
            // Connecting can fails due the ports not being forwarded or due to the
            // server socket not being started yet.
            // To be able to detect the server socket as running, a device must connected to the PC
            // and ADBVApplication configured android app must run on the device.
            final Socket deviceSocket = new Socket("localhost", PC_PORT);

            // Requesting to connect
            new PrintWriter(deviceSocket.getOutputStream(), true)
                    .println(new Data(Data.CONNECTION_REQUEST, "", "").toJSON().toString());
            Data recivedData = new Data(new JSONObject(
                    new BufferedReader(new InputStreamReader(deviceSocket.getInputStream())).readLine()));
            if (recivedData.getStatus() == Data.CONNECTION_ACCEPTED) {

                // Adding a shudown hook to disconnect the adb connection and close the socket connection
                Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

                    @Override
                    public void run() {
                        killServer();
                        try {
                            deviceSocket.shutdownInput();
                            deviceSocket.shutdownOutput();
                            deviceSocket.close();
                        } catch (IOException ex) {
                        }
                    }
                }));

                // Returning an IOManager created for this connection
                return new IOManager(deviceSocket);
            }
        } catch (IOException ex) {
            prepareADB();
        } catch (NullPointerException ex) {
            prepareADB();
        } catch (JSONException ex) {
            prepareADB();
        }
    }
}

From source file:com.hulaki.smtp.api.ApiClient.java

private String sendRequestToApiServer(ApiRequest request) {
    try {//from w  w w. j  a v  a  2s  .  c  o  m
        Socket clientSocket = new Socket(this.apiServerHostname, this.apiServerPort);
        DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());

        String requestString = request.toRequestString() + "\n";
        logger.trace(requestString);
        out.writeBytes(requestString);
        StringBuilder response = new StringBuilder();
        logger.trace(response.toString());

        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine).append("\n");
        }
        clientSocket.close();
        return response.toString();
    } catch (ConnectException e) {
        throw new ApiException("SMTP mock not available at " + apiServerHostname + ":" + apiServerPort);
    } catch (IOException e) {
        throw new ApiException(e);
    }
}

From source file:com.baidu.qa.service.test.client.SoapReqImpl.java

private static String sendSoap(String hosturl, String ip, int port, String action, String method, String xml,
        boolean isHttps) throws Exception {
    if (isHttps) {
        return sendSoapViaHttps(hosturl, ip, port, action, method, xml);
    }//from   www.j a  va2 s  . co m

    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");// must be UTF-8
    HttpProtocolParams.setUserAgent(params, "itest-by-HttpCore/4.2");

    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Required protocol interceptors
            new RequestContent(), new RequestTargetHost(),
            // Recommended protocol interceptors
            new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpContext context = new BasicHttpContext(null);

    // log.info("ip:port - " + ip + ":" + port );
    HttpHost host = new HttpHost(ip, port);// TODO

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    conn.setSocketTimeout(10000);
    HttpConnectionParams.setSoTimeout(params, 10000);
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

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

    String res = null;

    try {
        // HttpEntity requestBody = new
        // ByteArrayEntity(xml.getBytes("UTF-8"));// TODO
        byte[] b = xml.getBytes("UTF-8"); // must be UTF-8
        InputStream is = new ByteArrayInputStream(b, 0, b.length);

        HttpEntity requestBody = new InputStreamEntity(is, b.length,
                ContentType.create("text/xml;charset=UTF-8"));// must be
        // UTF-8

        // .create("application/xop+xml; charset=UTF-8; type=\"text/xml\""));//
        // TODO

        // RequestEntity re = new InputStreamRequestEntity(is, b.length,
        // "application/xop+xml; charset=UTF-8; type=\"text/xml\"");
        // postmethod.setRequestEntity(re);

        if (!conn.isOpen()) {
            Socket socket = new Socket(host.getHostName(), host.getPort());
            conn.bind(socket, params);
        }
        BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", action);

        // add the 3 headers below
        request.addHeader("Accept-Encoding", "gzip,deflate");
        request.addHeader("SOAPAction", hosturl + action + method);// SOAP action
        request.addHeader("uuid", "itest");// for editor token of DR-Api

        request.setEntity(requestBody);
        log.info(">> Request URI: " + request.getRequestLine().getUri());

        request.setParams(params);
        httpexecutor.preProcess(request, httpproc, context);
        HttpResponse response = httpexecutor.execute(request, conn, context);
        response.setParams(params);
        httpexecutor.postProcess(response, httpproc, context);

        log.info("<< Response: " + response.getStatusLine());

        String contentEncoding = null;
        Header ce = response.getEntity().getContentEncoding();
        if (ce != null) {
            contentEncoding = ce.getValue();
        }

        if (contentEncoding != null && contentEncoding.indexOf("gzip") != -1) {
            GZIPInputStream gzipin = new GZIPInputStream(response.getEntity().getContent());
            Scanner in = new Scanner(new InputStreamReader(gzipin, "UTF-8"));
            StringBuilder sb = new StringBuilder();
            while (in.hasNextLine()) {
                sb.append(in.nextLine()).append(System.getProperty("line.separator"));
            }
            res = sb.toString();
        } else {
            res = EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        log.info(res);

        log.info("==============");
        if (!connStrategy.keepAlive(response, context)) {
            conn.close();
        } else {
            log.info("Connection kept alive...");
        }
    } finally {
        try {
            conn.close();
        } catch (IOException e) {
        }
    }
    return res;
}

From source file:com.doculibre.constellio.utils.ConnectorManagerRequestUtils.java

public static Element sendPost(ConnectorManager connectorManager, String servletPath, Document document) {
    try {/*from w  w w .j  a v  a2  s.c  o m*/
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
        HttpProtocolParams.setUseExpectContinue(params, true);

        BasicHttpProcessor httpproc = new BasicHttpProcessor();
        // Required protocol interceptors
        httpproc.addInterceptor(new RequestContent());
        httpproc.addInterceptor(new RequestTargetHost());
        // Recommended protocol interceptors
        httpproc.addInterceptor(new RequestConnControl());
        httpproc.addInterceptor(new RequestUserAgent());
        httpproc.addInterceptor(new RequestExpectContinue());

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

        HttpContext context = new BasicHttpContext(null);

        URL connectorManagerURL = new URL(connectorManager.getUrl());
        HttpHost host = new HttpHost(connectorManagerURL.getHost(), connectorManagerURL.getPort());

        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

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

        try {
            HttpEntity requestBody;
            if (document != null) {
                //                 OutputFormat format = OutputFormat.createPrettyPrint();
                OutputFormat format = OutputFormat.createCompactFormat();
                StringWriter stringWriter = new StringWriter();
                XMLWriter xmlWriter = new XMLWriter(stringWriter, format);
                xmlWriter.write(document);
                String xmlAsString = stringWriter.toString();
                requestBody = new StringEntity(xmlAsString, "UTF-8");
            } else {
                requestBody = null;
            }
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }

            String target = connectorManager.getUrl() + servletPath;

            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", target);
            request.setEntity(requestBody);
            LOGGER.info(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            LOGGER.info("<< Response: " + response.getStatusLine());
            String entityText = EntityUtils.toString(response.getEntity());
            LOGGER.info(entityText);
            LOGGER.info("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                LOGGER.info("Connection kept alive...");
            }

            Document xml = DocumentHelper.parseText(entityText);
            return xml.getRootElement();
        } finally {
            conn.close();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.android.unit_tests.TestHttpService.java

/**
 * This test case executes a series of simple POST requests with content length 
 * delimited content. /*from  w  ww. j a v  a 2  s.  c o  m*/
 */
@LargeTest
public void testSimpleHttpPostsWithContentLength() throws Exception {

    int reqNo = 20;

    Random rnd = new Random();

    // Prepare some random data
    List testData = new ArrayList(reqNo);
    for (int i = 0; i < reqNo; i++) {
        int size = rnd.nextInt(5000);
        byte[] data = new byte[size];
        rnd.nextBytes(data);
        testData.add(data);
    }

    // Initialize the server-side request handler
    this.server.registerHandler("*", new HttpRequestHandler() {

        public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {

            if (request instanceof HttpEntityEnclosingRequest) {
                HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity();
                byte[] data = EntityUtils.toByteArray(incoming);

                ByteArrayEntity outgoing = new ByteArrayEntity(data);
                outgoing.setChunked(false);
                response.setEntity(outgoing);
            } else {
                StringEntity outgoing = new StringEntity("No content");
                response.setEntity(outgoing);
            }
        }

    });

    this.server.start();

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    HttpHost host = new HttpHost("localhost", this.server.getPort());

    try {
        for (int r = 0; r < reqNo; r++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, this.client.getParams());
            }

            BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/");
            byte[] data = (byte[]) testData.get(r);
            ByteArrayEntity outgoing = new ByteArrayEntity(data);
            post.setEntity(outgoing);

            HttpResponse response = this.client.execute(post, host, conn);
            byte[] received = EntityUtils.toByteArray(response.getEntity());
            byte[] expected = (byte[]) testData.get(r);

            assertEquals(expected.length, received.length);
            for (int i = 0; i < expected.length; i++) {
                assertEquals(expected[i], received[i]);
            }
            if (!this.client.keepAlive(response)) {
                conn.close();
            }
        }
        //Verify the connection metrics
        HttpConnectionMetrics cm = conn.getMetrics();
        assertEquals(reqNo, cm.getRequestCount());
        assertEquals(reqNo, cm.getResponseCount());

    } finally {
        conn.close();
        this.server.shutdown();
    }
}

From source file:com.lion328.xenonlauncher.minecraft.api.authentication.yggdrasil.YggdrasilMinecraftAuthenticator.java

private ResponseState sendRequest(String endpoint, String data) throws IOException, YggdrasilAPIException {
    URL url = new URL(serverURL, endpoint);

    // HttpURLConnection can only handle 2xx response code for headers
    // so it need to use HttpCore instead
    // maybe I could use an alternative like HttpClient
    // but for lightweight, I think is not a good idea

    BasicHttpEntity entity = new BasicHttpEntity();

    byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
    entity.setContent(new ByteArrayInputStream(dataBytes));
    entity.setContentLength(dataBytes.length);

    HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", url.getFile(),
            HttpVersion.HTTP_1_1);//from   w  ww .j a v a  2 s  .  c o m
    request.setHeader(new BasicHeader("Host", url.getHost()));
    request.setHeader(new BasicHeader("Content-Type", "application/json"));
    request.setHeader(new BasicHeader("Content-Length", Integer.toString(dataBytes.length)));

    request.setEntity(entity);

    Socket s;
    int port = url.getPort();

    if (url.getProtocol().equals("https")) {
        if (port == -1) {
            port = 443;
        }

        s = SSLSocketFactory.getDefault().createSocket(url.getHost(), port);
    } else {
        if (port == -1) {
            port = 80;
        }

        s = new Socket(url.getHost(), port);
    }

    DefaultBHttpClientConnection connection = new DefaultBHttpClientConnection(8192);
    connection.bind(s);

    try {
        connection.sendRequestHeader(request);
        connection.sendRequestEntity(request);

        HttpResponse response = connection.receiveResponseHeader();
        connection.receiveResponseEntity(response);

        if (!response.getFirstHeader("Content-Type").getValue().startsWith("application/json")) {
            throw new InvalidImplementationException("Invalid content type");
        }

        InputStream stream = response.getEntity().getContent();
        StringBuilder sb = new StringBuilder();
        int b;

        while ((b = stream.read()) != -1) {
            sb.append((char) b);
        }

        return new ResponseState(response.getStatusLine().getStatusCode(), sb.toString());
    } catch (HttpException e) {
        throw new IOException(e);
    }
}

From source file:com.mnxfst.testing.activities.http.TestHTTPRequestActivity.java

public void testExecuteHTTPRequest() throws HttpException, IOException {

    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, false);

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
    HttpContext context = new BasicHttpContext(null);
    HttpHost host = new HttpHost("www.heise.de", 80);

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

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

    try {/*from  w  w w  .  j  av  a  2 s  .  c  o m*/

        HttpEntity[] requestBodies = { new StringEntity("This is the first test request", "UTF-8"),
                new ByteArrayEntity("This is the second test request".getBytes("UTF-8")),
                new InputStreamEntity(new ByteArrayInputStream(
                        "This is the third test request (will be chunked)".getBytes("UTF-8")), -1) };

        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                // Required protocol interceptors
                new RequestContent(), new RequestTargetHost(),
                // Recommended protocol interceptors
                new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

        for (int i = 0; i < requestBodies.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");
            request.setEntity(requestBodies[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            System.out.println("<< Response: " + response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }

}