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:fr.enseirb.odroidx.videomanager.Uploader.java

public void doUpload(Uri myFile) {
    createNotification();/*from w  w w  .ja  v  a 2 s  .com*/
    File f = new File(myFile.getPath());
    SendName(f.getName().replace(' ', '-'));
    Log.e(getClass().getSimpleName(), "test: " + f.exists());
    if (f.exists()) {
        Socket s;
        try {
            Log.e(getClass().getSimpleName(), "test: " + server_ip);
            s = new Socket(InetAddress.getByName(server_ip), 5088);// Bug
            // using
            // variable
            // port
            OutputStream fluxsortie = s.getOutputStream();
            int nb_parts = (int) (f.length() / PART_SIZE);

            InputStream in = new BufferedInputStream(new FileInputStream(f));
            ByteArrayOutputStream byte_array = new ByteArrayOutputStream();
            BufferedOutputStream buffer = new BufferedOutputStream(byte_array);

            byte[] to_write = new byte[PART_SIZE];
            for (int i = 0; i < nb_parts; i++) {
                in.read(to_write, 0, PART_SIZE);
                buffer.write(to_write);
                buffer.flush();
                fluxsortie.write(byte_array.toByteArray());
                byte_array.reset();
                if ((i % 250) == 0) {
                    mBuilder.setProgress(nb_parts, i, false);
                    mNotifyManager.notify(NOTIFY_ID, mBuilder.getNotification());
                }
            }
            int remaining = (int) (f.length() - nb_parts * PART_SIZE);
            in.read(to_write, 0, remaining);
            buffer.write(to_write);
            buffer.flush();
            fluxsortie.write(byte_array.toByteArray());
            byte_array.reset();
            buffer.close();
            fluxsortie.close();
            in.close();
            s.close();
        } catch (ConnectException e) {
            if (STATUS != HTTP_SERVER)
                STATUS = CONNECTION_ERROR;
            e.printStackTrace();
        } catch (UnknownHostException e) {
            if (STATUS != HTTP_SERVER)
                STATUS = UNKNOWN;
            Log.i(getClass().getSimpleName(), "Unknown host");
            e.printStackTrace();
        } catch (IOException e) {
            if (STATUS != HTTP_SERVER)
                STATUS = CONNECTION_ERROR;
            e.printStackTrace();
        }
    }
}

From source file:disko.flow.analyzers.socket.SocketReceiver.java

private Message readMessage(ServerSocket serverSocket) {
    while (true) {
        Socket clientSocket = null;
        ObjectInputStream in = null;
        try {//from   www.  j  a  v  a  2s  .c o m
            clientSocket = serverSocket.accept();
            in = new ObjectInputStream(clientSocket.getInputStream());
            Message message = null;
            try {
                message = (Message) in.readObject();
            } catch (IOException e) {
                log.error("Error reading object.", e);
                continue;
            } catch (ClassNotFoundException e) {
                log.error("Class not found.", e);
                continue;
            }
            // while (in.read() != -1);
            // if (in.available() > 0)
            // {
            // System.err.println("OOPS, MORE THAT ON SOCKET HASN'T BEEN
            // READ: " + in.available());
            // while (in.available() > 0)
            // in.read();
            // }
            return message;
        } catch (SocketTimeoutException ex) {
            if (Thread.interrupted())
                return null;
        } catch (InterruptedIOException e) // this doesn't really work, that's why we put an Socket timeout and we check for interruption
        {
            return null;
        } catch (IOException e) {
            log.error("Could not listen on port: " + port, e);
        } finally {
            if (in != null)
                try {
                    in.close();
                } catch (Throwable t) {
                    log.error("While closing receiver input.", t);
                }
            if (clientSocket != null)
                try {
                    clientSocket.close();
                } catch (Throwable t) {
                    log.error("While closing receiver socket.", t);
                }
        }
    }
}

From source file:com.isecpartners.gizmo.HttpRequest.java

void passThroughAllBits() {
    try {/*w  ww  . jav  a  2s. c  o m*/
        Socket destinationHost = new Socket(host, port);
        byte[] buf = new byte[1024];
        boolean didNothing = true;
        while (!this.sock.isClosed() && !destinationHost.isClosed()) {
            didNothing = true;
            if (sock.getInputStream().available() > 0) {
                int b = sock.getInputStream().read(buf);
                destinationHost.getOutputStream().write(buf, 0, b);
                didNothing = false;
            }
            if (destinationHost.getInputStream().available() > 0) {
                int b = destinationHost.getInputStream().read(buf);
                sock.getOutputStream().write(buf, 0, b);
                didNothing = false;
            }
            if (didNothing) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        this.sock.close();
        destinationHost.close();
    } catch (UnknownHostException ex) {
        Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.envirover.spl.SPLGroungControlTest.java

@Test
public void testMOMessagePipeline()
        throws URISyntaxException, ClientProtocolException, IOException, InterruptedException {
    System.out.println("MO TEST: Testing MO message pipeline...");

    Thread.sleep(1000);/*from w  w  w  .j  av a2s.  c  o m*/

    Thread mavlinkThread = new Thread(new Runnable() {
        public void run() {
            Socket client = null;

            try {
                System.out.printf("MO TEST: Connecting to tcp://%s:%d",
                        InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());
                System.out.println();

                client = new Socket(InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());

                System.out.printf("MO TEST: Connected tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(),
                        config.getMAVLinkPort());
                System.out.println();

                Parser parser = new Parser();
                DataInputStream in = new DataInputStream(client.getInputStream());
                while (true) {
                    MAVLinkPacket packet;
                    do {
                        int c = in.readUnsignedByte();
                        packet = parser.mavlink_parse_char(c);
                    } while (packet == null);

                    System.out.printf("MO TEST: MAVLink message received: msgid = %d", packet.msgid);
                    System.out.println();

                    Thread.sleep(100);
                }
            } catch (InterruptedException ex) {
                return;
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    mavlinkThread.start();

    HttpClient httpclient = HttpClients.createDefault();

    URIBuilder builder = new URIBuilder();
    builder.setScheme("http");
    builder.setHost(InetAddress.getLocalHost().getHostAddress());
    builder.setPort(config.getRockblockPort());
    builder.setPath(config.getHttpContext());

    URI uri = builder.build();
    HttpPost httppost = new HttpPost(uri);

    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair("imei", config.getRockBlockIMEI()));
    params.add(new BasicNameValuePair("momsn", "12345"));
    params.add(new BasicNameValuePair("transmit_time", "12-10-10 10:41:50"));
    params.add(new BasicNameValuePair("iridium_latitude", "52.3867"));
    params.add(new BasicNameValuePair("iridium_longitude", "0.2938"));
    params.add(new BasicNameValuePair("iridium_cep", "9"));
    params.add(new BasicNameValuePair("data", Hex.encodeHexString(getSamplePacket().encodePacket())));
    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    // Execute and get the response.
    System.out.printf("MO TEST: Sending test message to %s", uri.toString());
    System.out.println();

    HttpResponse response = httpclient.execute(httppost);

    if (response.getStatusLine().getStatusCode() != 200) {
        fail(String.format("RockBLOCK HTTP message handler status code = %d.",
                response.getStatusLine().getStatusCode()));
    }

    HttpEntity entity = response.getEntity();

    if (entity != null) {
        InputStream responseStream = entity.getContent();
        try {
            String responseString = IOUtils.toString(responseStream);
            System.out.println(responseString);
        } finally {
            responseStream.close();
        }
    }

    Thread.sleep(1000);

    mavlinkThread.interrupt();
    System.out.println("MO TEST: Complete.");
}

From source file:com.vendsy.bartsy.venue.BartsyApplication.java

public void printOrders(ArrayList<Order> addedOrders) {

    String ip = Utilities.loadPref(this, R.string.config_printer_ip, null);

    if (ip == null) {
        Log.e(TAG, "Printer IP address not configured");
        return;/*from   www.  j  a  va  2s  .c  om*/
    }

    try {
        for (Order order : addedOrders) {
            Socket sock = new Socket(ip, 9100);
            PrintWriter oStream = new PrintWriter(sock.getOutputStream());
            order.println(oStream);
            oStream.print("\n\n\n");
            oStream.close();
            sock.close();
        }
    } catch (UnknownHostException e) {
        e.printStackTrace();
        Log.e(TAG, "Unknown host");
    } catch (IOException e) {
        e.printStackTrace();
        Log.e(TAG, "I/O error");
    }
}

From source file:gov.hhs.fha.nhinc.lift.clientController.SocketClientManagerController.java

@Override
public final void run() {

    while (true) {
        Socket socket = null;
        InputStream in = null;// ww  w  . j a va 2  s.co  m
        URI writtenFile = null;
        String errorMesg = null;
        LiftMessage mesg = null;
        try {

            socket = server.accept();
            while (socket == null) {
                socket = server.accept();
            }
            in = socket.getInputStream();
            log.debug("Server " + server.getInetAddress() + " connecting to socket " + socket.getInetAddress()
                    + ": " + socket.getPort());

            InterProcessSocketProtocol processSocket = new InterProcessSocketProtocol();
            String message = processSocket.readData(in);
            log.info("SocketClientManagerController received message: " + message);
            if (message != null) {
                mesg = (LiftMessage) JaxbUtil.unmarshalFromReader(new StringReader(message), LiftMessage.class);
                System.out.println("Setting " + mesg.getRequest().getRequest() + " to in progress");
                mesgState.add(mesg.getRequest().getRequest());
                writtenFile = manager.startClient(mesg, this);
            }
        } catch (JAXBException ex) {
            errorMesg = "Client is unable to process LiftMessage " + ex.getMessage();
            log.error(errorMesg);
        } catch (IOException e) {
            errorMesg = "Client is unable to process incoming socket information " + e.getMessage();
            log.error(errorMesg);
        } finally {
            if (socket != null) {
                try {
                    log.debug("Closing socket " + socket);
                    socket.close();
                } catch (IOException ex) {
                    log.warn("Unable to close socket " + socket);
                }
            }

            if (writtenFile != null) {
                reportSuccess(mesg.getRequest().getRequest(), writtenFile);
            } else {
                if (mesg != null && mesg.getRequest() != null && mesg.getRequest().getRequest() != null) {
                    reportFailure(mesg.getRequest().getRequest(), errorMesg);
                } else {
                    reportFailure(null, errorMesg);
                }

            }

        }
    }
}

From source file:com.vkassin.mtrade.Common.java

public static void login(final Context ctx) {

    // ctx = Common.app_ctx;
    Common.connected = false;//from ww  w . j  a v a 2  s .co  m

    if (inLogin)
        return;

    inLogin = true;

    if (Common.mainActivity != null)
        Common.mainActivity.handler.sendMessage(
                Message.obtain(Common.mainActivity.handler, Common.mainActivity.DISMISS_PROGRESS_DIALOG));

    // while(true) {

    final Dialog dialog = new Dialog(ctx);
    dialog.setContentView(R.layout.login_dialog);
    dialog.setTitle(R.string.LoginDialogTitle);
    dialog.setCancelable(false);

    final EditText nametxt = (EditText) dialog.findViewById(R.id.loginnameedit);
    final EditText passtxt = (EditText) dialog.findViewById(R.id.passwordedit);
    final EditText passtxt1 = (EditText) dialog.findViewById(R.id.passwordedit1);
    final EditText passtxt2 = (EditText) dialog.findViewById(R.id.passwordedit2);
    final EditText mailtxt = (EditText) dialog.findViewById(R.id.emailedit2);

    String nam = myaccount.get("name");
    Common.oldName = nam;

    if (nam != null) {

        nametxt.setText(nam);
        passtxt.requestFocus();
    }

    Button customDialog_Register = (Button) dialog.findViewById(R.id.goregister);
    customDialog_Register.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            dialog.setTitle(R.string.LoginDialogTitle1);
            final LinearLayout layreg = (LinearLayout) dialog.findViewById(R.id.reglayout354);
            layreg.setVisibility(View.VISIBLE);
            final LinearLayout laylog = (LinearLayout) dialog.findViewById(R.id.loginlayout543);
            laylog.setVisibility(View.GONE);
        }

    });

    Button customDialog_Register1 = (Button) dialog.findViewById(R.id.goregister1);
    customDialog_Register1.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            if (mailtxt.getText().length() < 1) {

                Toast toast = Toast.makeText(mainActivity, R.string.CorrectEmail, Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                toast.show();

                return;
            }

            if (passtxt1.getText().length() < 1) {

                Toast toast = Toast.makeText(mainActivity, R.string.CorrectPassword, Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                toast.show();
                return;
            }

            if (!passtxt2.getText().toString().equals(passtxt1.getText().toString())) {

                Toast toast = Toast.makeText(mainActivity, R.string.CorrectPassword1, Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                toast.show();
                return;
            }

            try {

                Socket sock = new Socket(ip_addr, port_register);

                JSONObject msg = new JSONObject();
                msg.put("objType", Common.MSG_REGISTER);
                msg.put("time", Calendar.getInstance().getTimeInMillis());
                msg.put("user", mailtxt.getText().toString());
                msg.put("passwd", passtxt1.getText().toString());
                msg.put("version", Common.PROTOCOL_VERSION);
                msg.put("sign", sign(mailtxt.getText().toString(), passtxt1.getText().toString()));

                byte[] array = msg.toString().getBytes();
                ByteBuffer buff = ByteBuffer.allocate(array.length + 4);
                buff.putInt(array.length);
                buff.put(array);
                sock.getOutputStream().write(buff.array());

                ByteBuffer buff1 = ByteBuffer.allocate(4);
                buff1.put(readMsg(sock.getInputStream(), 4));
                buff1.position(0);
                int pkgSize = buff1.getInt();
                // Log.i(TAG, "size = "+pkgSize);
                String s = new String(readMsg(sock.getInputStream(), pkgSize));

                sock.close();

                JSONObject jo = new JSONObject(s);

                Log.i(TAG, "register answer = " + jo);

                int t = jo.getInt("status");
                switch (t) {

                case 1:
                    Toast toast = Toast.makeText(mainActivity, R.string.RegisterStatus1, Toast.LENGTH_LONG);
                    toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                    toast.show();

                    dialog.setTitle(R.string.LoginDialogTitle);
                    final LinearLayout layreg = (LinearLayout) dialog.findViewById(R.id.reglayout354);
                    layreg.setVisibility(View.GONE);
                    final LinearLayout laylog = (LinearLayout) dialog.findViewById(R.id.loginlayout543);
                    laylog.setVisibility(View.VISIBLE);

                    nametxt.setText(mailtxt.getText());
                    break;

                case -2:
                    Toast toast1 = Toast.makeText(mainActivity, R.string.RegisterStatus3, Toast.LENGTH_LONG);
                    toast1.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                    toast1.show();
                    break;

                default:
                    Toast toast2 = Toast.makeText(mainActivity, R.string.RegisterStatus2, Toast.LENGTH_LONG);
                    toast2.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                    toast2.show();
                    break;

                }

            } catch (Exception e) {

                e.printStackTrace();
                Log.e(TAG, "Error in registration process!!", e);

                Toast toast = Toast.makeText(mainActivity, R.string.ConnectError, Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                toast.show();

            }

        }

    });

    Button customDialog_CancelReg = (Button) dialog.findViewById(R.id.cancelreg);
    customDialog_CancelReg.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            dialog.setTitle(R.string.LoginDialogTitle);
            final LinearLayout layreg = (LinearLayout) dialog.findViewById(R.id.reglayout354);
            layreg.setVisibility(View.GONE);
            final LinearLayout laylog = (LinearLayout) dialog.findViewById(R.id.loginlayout543);
            laylog.setVisibility(View.VISIBLE);

        }

    });

    Button customDialog_Dismiss = (Button) dialog.findViewById(R.id.gologin);
    customDialog_Dismiss.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            final RadioButton bu0 = (RadioButton) dialog.findViewById(R.id.lradio0);
            Common.isSSL = bu0.isChecked();

            inLogin = false;

            JSONObject msg = new JSONObject();
            try {

                msg.put("objType", Common.LOGOUT);
                msg.put("time", Calendar.getInstance().getTimeInMillis());
                msg.put("version", Common.PROTOCOL_VERSION);
                msg.put("status", 1);
                mainActivity.writeJSONMsg(msg);
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, "Error! Cannot create JSON logout object", e);
            }

            myaccount.put("name", nametxt.getText().toString());
            myaccount.put("password", passtxt.getText().toString());

            Log.i(TAG,
                    "myaccount username: " + myaccount.get("name") + " password: " + myaccount.get("password"));

            dialog.dismiss();
            mainActivity.stop();
            // saveAccountDetails();
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            loginFromDialog = true;
            //            mainActivity.refresh();

            Common.keypassword(ctx);
        }

    });

    dialog.show();
    // Common.confChanged = false;
    // }//while(true);

}

From source file:com.symbian.driver.plugins.reboot.Activator.java

/**
 * @param switchState/*from w w  w . j  av a2s .co  m*/
 * @throws IOException
 */
private synchronized void switchOp(String switchState) throws IOException {
    LOGGER.log(Level.INFO, "Activator::switchOp");

    // Alternative being "TelnetSwitch"
    if (method.compareToIgnoreCase("PortTalk") == 0)// ATX power
    {
        String state = switchState == "2" ? "OFF" : "ON";
        File hardwareSwitchFile = JarUtils.extractResource(Activator.class, "/resource/HardwareSwitch.exe");
        if (hardwareSwitchFile.isFile()) {
            Process p = Runtime.getRuntime()
                    .exec("cmd.exe /c " + hardwareSwitchFile.getAbsolutePath() + " " + state);
            BufferedReader iBufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String lOutput = null;
            StringBuffer iOutputBuffer = new StringBuffer();
            while ((lOutput = iBufferedReader.readLine()) != null) {
                lOutput += System.getProperty("line.separator");
                iOutputBuffer.append(lOutput);
                // Parse for errors and redirect to appropriate buffer.
            }
            LOGGER.info(iOutputBuffer.toString());
        } else {
            LOGGER.warning(hardwareSwitchFile.getAbsolutePath() + " was not found");
        }
    } else {

        String responseLine = "";
        String[] states = { "User Name :", "Password  :", "Control Console", "Device Manager",
                "Outlet Management", "Outlet Control/Configuration", "Outlet " + outletNo, "Control Outlet",
                "Immediate Off", "Press <ENTER> to continue..." };

        String[] answers = { userName, password, "1", "2", "1", outletNo, "1", switchState, "YES", "\n" };

        Socket sock = new Socket(hostAddr, 23);
        PrintWriter dataToTelnetServer = new PrintWriter(sock.getOutputStream(), true);
        BufferedReader dataFromTelnetServer = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        // start the state machine...
        int state = 0;
        long lastStateChng = System.currentTimeMillis();
        while (state < states.length) {
            while (dataFromTelnetServer.ready()) {
                char nextChar = (char) dataFromTelnetServer.read();
                responseLine += nextChar;
            }
            LOGGER.log(Level.FINE, responseLine);
            if (responseLine.contains(states[state])) // sort of on
            {

                LOGGER.log(Level.FINE, "answers[" + state + "]:" + answers[state]);
                dataToTelnetServer.println(answers[state]);
                state++;
                lastStateChng = System.currentTimeMillis();
                continue;
            }
            if ((System.currentTimeMillis() - lastStateChng) > 10000) {
                // too much time since last change of state...
                // we have lost the connection...
                LOGGER.log(Level.SEVERE, "Lost telnet connection");
                break;
            }
        }
        responseLine = "";
        dataToTelnetServer.flush();
        dataToTelnetServer.close();
        dataFromTelnetServer.close();
        sock.close();
    }
}

From source file:com.esri.geoevent.test.tools.RunTcpInTcpOutTest.java

public void send(String server, Integer port, Long numEvents, Integer rate) {
    Random rnd = new Random();
    BufferedReader br = null;//  www  .ja  v  a2  s . com
    LocalDateTime st = null;

    try {
        Socket sckt = new Socket(server, port);
        OutputStream os = sckt.getOutputStream();
        //PrintWriter sckt_out = new PrintWriter(os, true);

        Integer cnt = 0;

        st = LocalDateTime.now();

        Double ns_delay = 1000000000.0 / (double) rate;

        long ns = ns_delay.longValue();
        if (ns < 0) {
            ns = 0;
        }

        while (cnt < numEvents) {
            cnt += 1;
            LocalDateTime ct = LocalDateTime.now();
            String dtg = ct.toString();
            Double lat = 180 * rnd.nextDouble() - 90.0;
            Double lon = 360 * rnd.nextDouble() - 180.0;
            String line = "RandomPoint," + cnt.toString() + "," + dtg + ",\"" + lon.toString() + ","
                    + lat.toString() + "\"," + cnt.toString() + "\n";

            final long stime = System.nanoTime();

            long etime = 0;
            do {
                etime = System.nanoTime();
            } while (stime + ns >= etime);

            if (cnt % 1000 == 0) {
                //System.out.println(cnt);
            }

            //sckt_out.write(line);
            os.write(line.getBytes());
            os.flush();

        }

        if (st != null) {
            LocalDateTime et = LocalDateTime.now();

            Duration delta = Duration.between(st, et);

            Double elapsed_seconds = (double) delta.getSeconds() + delta.getNano() / 1000000000.0;

            send_rate = (double) numEvents / elapsed_seconds;
        }

        //sckt_out.close();
        sckt.close();
        os = null;
        //sckt_out = null;

    } catch (Exception e) {
        System.err.println(e.getMessage());
        send_rate = -1.0;
    } finally {
        try {
            br.close();
        } catch (Exception e) {
            //
        }

        this.send_rate = send_rate;

    }

}

From source file:com.alexkli.jhb.Worker.java

@Override
public void run() {
    try {//w ww .  j  a v a  2  s  .  c o  m
        while (true) {
            long start = System.nanoTime();

            QueueItem<HttpRequestBase> item = queue.take();

            idleAvg.add(System.nanoTime() - start);

            if (item.isPoisonPill()) {
                return;
            }

            HttpRequestBase request = item.getRequest();

            if ("java".equals(config.client)) {
                System.setProperty("http.keepAlive", "false");

                item.sent();

                try {
                    HttpURLConnection http = (HttpURLConnection) new URL(request.getURI().toString())
                            .openConnection();
                    http.setConnectTimeout(5000);
                    http.setReadTimeout(5000);
                    int statusCode = http.getResponseCode();

                    consumeAndCloseStream(http.getInputStream());

                    if (statusCode == 200) {
                        item.done();
                    } else {
                        item.failed();
                    }
                } catch (IOException e) {
                    System.err.println("Failed request: " + e.getMessage());
                    e.printStackTrace();
                    //                        System.exit(2);
                    item.failed();
                }
            } else if ("ahc".equals(config.client)) {
                try {
                    item.sent();

                    try (CloseableHttpResponse response = httpClient.execute(request, context)) {
                        int statusCode = response.getStatusLine().getStatusCode();
                        if (statusCode == 200) {
                            item.done();
                        } else {
                            item.failed();
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Failed request: " + e.getMessage());
                    item.failed();
                }
            } else if ("fast".equals(config.client)) {
                try {
                    URI uri = request.getURI();

                    item.sent();

                    InetAddress addr = InetAddress.getByName(uri.getHost());
                    Socket socket = new Socket(addr, uri.getPort());
                    PrintWriter out = new PrintWriter(socket.getOutputStream());
                    //                        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    // send an HTTP request to the web server
                    out.println("GET / HTTP/1.1");
                    out.append("Host: ").append(uri.getHost()).append(":").println(uri.getPort());
                    out.println("Connection: Close");
                    out.println();
                    out.flush();

                    // read the response
                    consumeAndCloseStream(socket.getInputStream());
                    //                        boolean loop = true;
                    //                        StringBuilder sb = new StringBuilder(8096);
                    //                        while (loop) {
                    //                            if (in.ready()) {
                    //                                int i = 0;
                    //                                while (i != -1) {
                    //                                    i = in.read();
                    //                                    sb.append((char) i);
                    //                                }
                    //                                loop = false;
                    //                            }
                    //                        }
                    item.done();
                    socket.close();

                } catch (IOException e) {
                    e.printStackTrace();
                    item.failed();
                }
            } else if ("nio".equals(config.client)) {
                URI uri = request.getURI();

                item.sent();

                String requestBody = "GET / HTTP/1.1\n" + "Host: " + uri.getHost() + ":" + uri.getPort() + "\n"
                        + "Connection: Close\n\n";

                try {
                    InetSocketAddress addr = new InetSocketAddress(uri.getHost(), uri.getPort());
                    SocketChannel channel = SocketChannel.open();
                    channel.socket().setSoTimeout(5000);
                    channel.connect(addr);

                    ByteBuffer msg = ByteBuffer.wrap(requestBody.getBytes());
                    channel.write(msg);
                    msg.clear();

                    ByteBuffer buf = ByteBuffer.allocate(1024);

                    int count;
                    while ((count = channel.read(buf)) != -1) {
                        buf.flip();

                        byte[] bytes = new byte[count];
                        buf.get(bytes);

                        buf.clear();
                    }
                    channel.close();

                    item.done();

                } catch (IOException e) {
                    e.printStackTrace();
                    item.failed();
                }
            }
        }
    } catch (InterruptedException e) {
        System.err.println("Worker thread [" + this.toString() + "] was interrupted: " + e.getMessage());
    }
}