Example usage for java.net Socket getOutputStream

List of usage examples for java.net Socket getOutputStream

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream for this socket.

Usage

From source file:ext.services.network.TestNetworkUtils.java

/**
 * Test get connection url proxy with proxy.
 * /*from  w w  w  . ja v  a  2 s.  c  o m*/
 *
 * @throws Exception the exception
 */
public void testGetConnectionURLProxyWithProxy() throws Exception {
    final ServerSocket socket = new ServerSocket(PROXY_PORT);
    Thread thread = new Thread("ProxySocketAcceptThread") {
        @Override
        public void run() {
            try {
                while (!bStop) {
                    Socket sock = socket.accept();
                    Log.debug("Accepted connection, sending back garbage and close socket...");
                    sock.getOutputStream().write(1);
                    sock.close();
                }
            } catch (IOException e) {
                Log.error(e);
            }
        }
    };
    thread.setDaemon(true); // to finish tests even if this is still running
    thread.start();
    Log.debug("Using local port: " + socket.getLocalPort());
    try {
        // useful content when inet access is allowed
        Conf.setProperty(Const.CONF_NETWORK_NONE_INTERNET_ACCESS, "false");
        HttpURLConnection connection = NetworkUtils.getConnection(new java.net.URL(URL),
                new Proxy(Type.SOCKS, "localhost", socket.getLocalPort(), "user", "password"));
        assertNotNull(connection);
        connection.disconnect();
    } finally {
        bStop = true;
        socket.close();
        thread.join();
    }
}

From source file:com.alibaba.wasp.zookeeper.ZKUtil.java

/**
 * Gets the statistics from the given server.
 *
 * @param server//from   w  w  w.  ja v  a2s  . c  o  m
 *          The server to get the statistics from.
 * @param timeout
 *          The socket timeout to use.
 * @return The array of response strings.
 * @throws java.io.IOException
 *           When the socket communication fails.
 */
public static String[] getServerStats(String server, int timeout) throws IOException {
    String[] sp = server.split(":");
    if (sp == null || sp.length == 0) {
        return null;
    }

    String host = sp[0];
    int port = sp.length > 1 ? Integer.parseInt(sp[1]) : HConstants.DEFAULT_ZOOKEPER_CLIENT_PORT;

    Socket socket = new Socket();
    InetSocketAddress sockAddr = new InetSocketAddress(host, port);
    socket.connect(sockAddr, timeout);

    socket.setSoTimeout(timeout);
    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out.println("stat");
    out.flush();
    ArrayList<String> res = new ArrayList<String>();
    while (true) {
        String line = in.readLine();
        if (line != null) {
            res.add(line);
        } else {
            break;
        }
    }
    socket.close();
    return res.toArray(new String[res.size()]);
}

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

@Override
public void run() {
    try {//from   ww w  . j  a  va 2s  .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());
    }
}

From source file:fitnesse.FitNesseExpediter.java

public FitNesseExpediter(Socket socket, FitNesseContext context, ExecutorService executorService,
        long requestParsingTimeLimit) throws IOException {
    this.context = context;
    this.socket = socket;
    this.executorService = executorService;
    input = socket.getInputStream();//ww w .  ja v a 2 s  .c o m
    output = socket.getOutputStream();
    this.requestParsingTimeLimit = requestParsingTimeLimit;
}

From source file:de.kapsi.net.daap.bio.DaapConnectionBIO.java

public DaapConnectionBIO(DaapServerBIO server, Socket socket) throws IOException {
    super(server);

    this.server = server;
    this.socket = socket;

    in = new BufferedInputStream(socket.getInputStream());
    out = socket.getOutputStream();

    connected = true;//from   ww  w. j a va  2  s.c  om
}

From source file:com.sixt.service.framework.registry.consul.RegistrationManager.java

protected void unregisterService() {
    if (!isRegistered.get()) {
        return;//from   w ww.  j a  va 2 s.com
    }
    try {
        logger.info("Unregistering {}", serviceName);
        String registryServer = serviceProps.getRegistryServer();
        int colon = registryServer.indexOf(':');
        String hostname = registryServer.substring(0, colon);
        int port = Integer.parseInt(registryServer.substring(colon + 1));
        Socket sock = new Socket(hostname, port);
        OutputStream out = sock.getOutputStream();
        out.write(unregisterString.getBytes());
        out.flush();
        sock.close();

        if (isShutdownHookRegistered.get()) {
            isShutdownHookRegistered.set(false);
        }
    } catch (Exception ex) {
        logger.error("Error unregistering from consul", ex);
    }
}

From source file:bankingclient.DNFrame.java

public DNFrame(MainFrame vmain) {

    initComponents();/*from   www .j  a  v  a 2 s  .  c om*/

    this.jTextField1.setText("");
    this.jTextField2.setText("");
    this.jTextField_cmt.setText("");
    this.jTextField_sdt.setText("");

    this.main = vmain;
    noAcc = new NewOrOldAccFrame(this);
    this.setVisible(false);
    jL_sdt.setVisible(false);
    jL_cmtnd.setVisible(false);
    jTextField_cmt.setVisible(false);
    jTextField_sdt.setVisible(false);

    jBt_dn.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            if (!jCheck_qmk.isSelected()) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(2);
                    dout.writeUTF(jTextField1.getText() + "\n" + jTextField2.getText());
                    dout.flush();
                    while (true) {
                        break;
                    }
                    DataInputStream din = new DataInputStream(client.getInputStream());
                    byte check = din.readByte();
                    if (check == 1) {
                        noAcc.setVisible(true);
                        DNFrame.this.setVisible(false);
                        noAcc.setMainCustomer(jTextField1.getText());

                    } else {
                        JOptionPane.showMessageDialog(new JFrame(),
                                "Tn ?ang Nhp Khng Tn Ti, hoac mat khau sai");
                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(rootPane, "C Li Kt Ni Mng....");
                }
            } else if ((!jTextField_cmt.getText().equals("")) && (!jTextField_sdt.getText().equals(""))
                    && (NumberUtils.isNumber(jTextField_cmt.getText()))
                    && (NumberUtils.isNumber(jTextField_sdt.getText()))) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(9);
                    dout.writeUTF(jTextField1.getText() + "\n" + jTextField_sdt.getText() + "\n"
                            + jTextField_cmt.getText());
                    dout.flush();
                    DataInputStream din = new DataInputStream(client.getInputStream());
                    byte check = din.readByte();
                    if (check == 1) {
                        noAcc.setVisible(true);
                        DNFrame.this.setVisible(false);
                        noAcc.setMainCustomer(jTextField1.getText());
                    } else {
                        JOptionPane.showMessageDialog(new JFrame(), "Khong dang nhap duoc, thong tin sai");
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else {
                JOptionPane.showMessageDialog(new JFrame(), "Can dien day du thong tin va dung mau");
            }
        }
    });
    jBt_ql.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            main.setVisible(true);
            DNFrame.this.setVisible(false);
        }
    });
    jCheck_qmk.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (jCheck_qmk.isSelected()) {
                jL_sdt.setVisible(true);
                jL_cmtnd.setVisible(true);
                jTextField_cmt.setVisible(true);
                jTextField_sdt.setVisible(true);
            } else {
                jL_sdt.setVisible(false);
                jL_cmtnd.setVisible(false);
                jTextField_cmt.setVisible(false);
                jTextField_sdt.setVisible(false);
            }
        }
    });
}

From source file:hd3gtv.as5kpc.protocol.ProtocolHandler.java

public ProtocolHandler(Socket socket) throws ParserConfigurationException, IOException {
    this.socket = socket;
    is = socket.getInputStream();//from   w  w w.j  av a2s .  co m
    os = socket.getOutputStream();
}

From source file:com.barchart.udt.AppServer.java

private static void copyFile(final Socket sock) {
    log.info("Inside copy file ");
    final Runnable runner = new Runnable() {
        public void run() {
            InputStream is = null;
            OutputStream os = null;
            try {
                is = sock.getInputStream();
                final byte[] bytes = new byte[1024];
                final int bytesRead = is.read(bytes);
                final String str = new String(bytes);
                if (str.startsWith("GET ")) {
                    int nameIndex = 0;
                    for (final byte b : bytes) {
                        if (b == '\n') {
                            break;
                        }//from w  ww .  j a v  a2 s . c o  m
                        nameIndex++;
                    }
                    // Eat the \n.
                    nameIndex++;
                    final String fileName = new String(bytes, 4, nameIndex).trim();
                    log.info("File name: " + fileName);
                    final File f = new File(fileName);
                    final FileInputStream fis = new FileInputStream(f);
                    os = sock.getOutputStream();

                    copy(fis, os, f.length());
                    os.close();
                    return;
                }
                int nameIndex = 0;
                int lengthIndex = 0;
                boolean foundFirst = false;
                //boolean foundSecond = false;
                for (final byte b : bytes) {
                    if (!foundFirst) {
                        nameIndex++;
                    }
                    lengthIndex++;
                    if (b == '\n') {
                        if (foundFirst) {
                            break;
                        }
                        foundFirst = true;
                    }
                }
                if (nameIndex < 2) {
                    // First bytes was a LF?
                    sock.close();
                    return;
                }
                String dataString = new String(bytes);
                int fileLengthIndex = dataString.indexOf("\n", nameIndex + 1);
                final String fileName = new String(bytes, 0, nameIndex).trim();
                final String lengthString = dataString.substring(nameIndex, fileLengthIndex);
                log.info("lengthString " + lengthString);
                final long length = Long.parseLong(lengthString);
                final File file = new File(fileName);
                os = new FileOutputStream(file);
                final int len = bytesRead - lengthIndex;
                if (len > 0) {
                    os.write(bytes, lengthIndex, len);
                }
                start = System.currentTimeMillis();
                copy(is, os, length);
            } catch (final IOException e) {
                log.info("Exception reading file...", e);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(os);
                IOUtils.closeQuietly(sock);
            }
        }
    };
    log.info("Executing copy...");
    readPool.execute(runner);
}

From source file:com.googlecode.jmxtrans.model.output.GraphiteWriterTests.java

@Test
public void socketInvalidatedWhenError() throws Exception {
    GenericKeyedObjectPool<InetSocketAddress, Socket> pool = mock(GenericKeyedObjectPool.class);
    Socket socket = mock(Socket.class);
    when(pool.borrowObject(Matchers.any(InetSocketAddress.class))).thenReturn(socket);
    UnflushableByteArrayOutputStream out = new UnflushableByteArrayOutputStream();
    when(socket.getOutputStream()).thenReturn(out);

    GraphiteWriter writer = GraphiteWriter.builder().setHost("localhost").setPort(2003).build();
    writer.setPool(pool);/*  w w  w .j  a va 2  s  .c o  m*/

    writer.doWrite(dummyServer(), dummyQuery(), dummyResults());
    Mockito.verify(pool).invalidateObject(Matchers.any(InetSocketAddress.class), Matchers.eq(socket));
    Mockito.verify(pool, Mockito.never()).returnObject(Matchers.any(InetSocketAddress.class),
            Matchers.eq(socket));
}