Example usage for java.net Socket getInputStream

List of usage examples for java.net Socket getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream for this socket.

Usage

From source file:com.twinsoft.convertigo.eclipse.learnproxy.http.HttpProxyWorker.java

private HttpResponse handleResponse(Socket destinationSocket, BufferedOutputStream proxyClientStream)
        throws IOException {
    HttpResponse response = new HttpResponse();
    BufferedInputStream responseInputStream = new BufferedInputStream(destinationSocket.getInputStream());
    int readInt;//from   w w  w . j  a va2  s .  c o  m
    int length = -1;
    String previousLine;
    byte b = -1;
    boolean hasCompleted = false;
    ArrayList<Byte> list = new ArrayList<Byte>(10000);
    ArrayList<Byte> responseContentList = new ArrayList<Byte>(10000);
    boolean isContent = false;
    boolean hasChunkedEncoding = false;
    int lineNo = 0;
    int lastCRPos = 0;
    while (!isInterrupted && !hasCompleted && (readInt = responseInputStream.read()) != -1) {
        b = (byte) readInt;
        list.add(new Byte(b));
        if (isContent) {
            responseContentList.add(new Byte(b));
        }
        proxyClientStream.write(readInt);
        if (b == 13) {
            if (list.size() > 1) {
                // try to analyze the previous line
                byte[] bytes = new byte[list.size() - lastCRPos];
                for (int i = lastCRPos; i < list.size() - 1; i++) {
                    bytes[i - lastCRPos] = list.get(i).byteValue();
                }
                // requests are always in ASCII
                previousLine = new String(bytes, "ISO-8859-1");
                if (lineNo == 0) {
                    // we must have here s.th. like 
                    // HTTP/1.0 200 OK
                    String[] components = previousLine.split(" ");
                    if (components.length > 2) {
                        response.setStatusCode(Integer.parseInt(components[1]));
                        response.setHttpVersion(components[0]);
                    }
                }
                if (previousLine.matches("^[Cc]ontent-[Ll]ength: .+")) {
                    String lengthStr = previousLine.substring(16, previousLine.length() - 1);
                    length = Integer.parseInt(lengthStr);
                }
                if (previousLine.matches("^[Tt]ransfer-[Ee]ncoding: [Cc]hunked.+")) {
                    hasChunkedEncoding = true;
                }
                //logger.debug("response: " + previousLine);
                // the CR should be ignored;
                lastCRPos = list.size() + 1;
                lineNo++;
            }
        }
        if (b == 10) {
            // check for two line breaks with form feed
            if (list.get(list.size() - 2).equals(new Byte((byte) 13))
                    && list.get(list.size() - 3).equals(new Byte((byte) 10))
                    && list.get(list.size() - 4).equals(new Byte((byte) 13))) {
                // section 4.3 of the http-spec states:
                // All responses to the HEAD request method
                // MUST NOT include a message-body, even though 
                // the presence of entity-header fields might lead
                // one to believe they do. All 1xx (informational),
                // 204 (no content), and 304 (not modified) responses
                // MUST NOT include a message-body. All other 
                // responses do include a message-body, although it 
                // MAY be of zero length.
                // (s. http://www.ietf.org/rfc/rfc2616.txt)
                if ("HEAD".equals(request.getMethod()) || response.getStatusCode() == 204
                        || response.getStatusCode() == 304
                        || (response.getStatusCode() > 99 && response.getStatusCode() < 200)) {
                    // no content allowed:
                    hasCompleted = true;
                } else if (length == 0) {
                    hasCompleted = true;
                } else if (length == -1) {
                    isContent = true;
                    if (hasChunkedEncoding) {
                        list.addAll(getAllChunks(responseInputStream, proxyClientStream));
                        hasCompleted = true;
                    }
                } else {
                    for (int i = 0; i < length; i++) {
                        readInt = responseInputStream.read();
                        b = (byte) readInt;
                        list.add(new Byte(b));
                        proxyClientStream.write(readInt);
                    }
                    hasCompleted = true;
                }
            }
        }
    }
    byte[] byteArray = getByteArrayFromList(list);
    //logger.debug("response: \nasText:\n" + new String(byteArray) + "as bytes:\n" + printByteArray(byteArray));

    response.setResponse(byteArray);

    return response;
}

From source file:net.jadler.JadlerStubbingIntegrationTest.java

@Test
@Ignore//  w w  w  . j av a  2 s. co  m
public void havingURISockets() throws IOException {
    onRequest().havingURIEqualTo("/").respond().withStatus(201);

    final Socket sock = new Socket("localhost", port());
    final OutputStream out = sock.getOutputStream();
    out.write("GET / HTTP/1.1\r\nHost:localhost\r\n\r\n".getBytes());

    InputStream in = sock.getInputStream();

    int b;
    while ((b = in.read()) != -1) {
        char res = (char) b;
        System.out.print(res);
    }
}

From source file:lockstep.LockstepServer.java

/**
 * Implements the handshake protocol server side, setting up the UDP 
 * connection, queues and threads for a specific client.
 * To be run in parallel threads, one for each client, as they need
 * to synchronize to correctly setup the lockstep protocol.
 * It signals success through a latch or failure through interruption to the
 * server thread.//from  ww  w. ja v a2 s  . com
 * 
 * @param tcpSocket Connection with the client, to be used in handshake only
 * @param firstFrameNumber Frame number to initialize the lockstep protocol
 * @param barrier Used for synchronization with concurrent handshake sessions
 * @param latch Used to signal the successful completion of the handshake session.
 * @param server Used to signal failure of the handshake sessions, via interruption.
 */
private void serverHandshakeProtocol(Socket tcpSocket, int firstFrameNumber, CyclicBarrier barrier,
        CountDownLatch latch, LockstepServer server) {
    try (ObjectOutputStream oout = new ObjectOutputStream(tcpSocket.getOutputStream());) {
        oout.flush();
        try (ObjectInputStream oin = new ObjectInputStream(tcpSocket.getInputStream());) {
            //Receive hello message from client and reply
            LOG.info("Waiting an hello from " + tcpSocket.getInetAddress().getHostAddress());
            oout.flush();
            ClientHello hello = (ClientHello) oin.readObject();
            LOG.info("Received an hello from " + tcpSocket.getInetAddress().getHostAddress());
            DatagramSocket udpSocket = new DatagramSocket();
            openSockets.add(udpSocket);
            InetSocketAddress clientUDPAddress = new InetSocketAddress(
                    tcpSocket.getInetAddress().getHostAddress(), hello.clientUDPPort);
            udpSocket.connect(clientUDPAddress);

            int assignedClientID;
            do {
                assignedClientID = (new Random()).nextInt(100000) + 10000;
            } while (!this.clientIDs.add(assignedClientID));

            LOG.info("Assigned hostID " + assignedClientID + " to "
                    + tcpSocket.getInetAddress().getHostAddress() + ", sending helloReply");
            ServerHelloReply helloReply = new ServerHelloReply(udpSocket.getLocalPort(), assignedClientID,
                    clientsNumber, firstFrameNumber);
            oout.writeObject(helloReply);

            ConcurrentHashMap<Integer, TransmissionQueue> clientTransmissionFrameQueues = new ConcurrentHashMap<>();
            this.transmissionFrameQueueTree.put(assignedClientID, clientTransmissionFrameQueues);

            ACKSet clientAckQueue = new ACKSet();
            ackQueues.put(assignedClientID, clientAckQueue);

            clientReceiveSetup(assignedClientID, udpSocket, firstFrameNumber, clientTransmissionFrameQueues);

            barrier.await();

            //Send second reply
            ClientsAnnouncement announcement = new ClientsAnnouncement();
            announcement.clientIDs = ArrayUtils.toPrimitive(this.clientIDs.toArray(new Integer[0]));
            oout.writeObject(announcement);

            clientTransmissionSetup(assignedClientID, firstFrameNumber, udpSocket,
                    clientTransmissionFrameQueues);

            //Wait for other handshakes to reach final step
            barrier.await();
            oout.writeObject(new SimulationStart());

            //Continue with execution
            latch.countDown();
        }
    } catch (IOException | ClassNotFoundException ioEx) {
        LOG.fatal("Exception at handshake with client");
        LOG.fatal(ioEx);
        server.interrupt();
    } catch (InterruptedException | BrokenBarrierException inEx) {
        //Interruptions come from failure in parallel handshake sessions, and signal termination
    }
}

From source file:com.apporiented.hermesftp.session.impl.FtpSessionContextImpl.java

/**
 * {@inheritDoc}/*from  w ww  .  j  a va2  s .  c o m*/
 */
public void setClientSocket(Socket clientSocket) throws IOException {
    this.clientSocket = clientSocket;
    this.clientResponseWriter = new LoggingWriter(new OutputStreamWriter(clientSocket.getOutputStream()), true);
    this.clientCmdReader = new LoggingReader(new InputStreamReader(clientSocket.getInputStream()));
}

From source file:it.crs4.pydoop.pipes.BinaryProtocol.java

/**
 * Create a proxy object that will speak the binary protocol on a socket.
 * Upward messages are passed on the specified handler and downward
 * downward messages are public methods on this object.
 * @param sock The socket to communicate on.
 * @param handler The handler for the received messages.
 * @param key The object to read keys into.
 * @param value The object to read values into.
 * @param config The job's configuration
 * @throws IOException//from   www. j  a v a 2 s.c om
 */
public BinaryProtocol(Socket sock, UpwardProtocol<K2, V2> handler, K2 key, V2 value, JobConf config)
        throws IOException {
    OutputStream raw = sock.getOutputStream();
    // If we are debugging, save a copy of the downlink commands to a file
    if (Submitter.getKeepCommandFile(config)) {
        raw = new TeeOutputStream("downlink.data", raw);
    }
    stream = new DataOutputStream(new BufferedOutputStream(raw, BUFFER_SIZE));
    uplink = new UplinkReaderThread<K2, V2>(sock.getInputStream(), handler, key, value);
    uplink.setName("pipe-uplink-handler");
    uplink.start();
}

From source file:bankingclient.DNFrame.java

public DNFrame(MainFrame vmain) {

    initComponents();//from   w w  w . j a v a  2  s .  c  o m

    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:org.apache.hadoop.dfs.TestBlockReplacement.java

private boolean replaceBlock(Block block, DatanodeInfo source, DatanodeInfo sourceProxy,
        DatanodeInfo destination) throws IOException {
    Socket sock = new Socket();
    sock.connect(NetUtils.createSocketAddr(sourceProxy.getName()), FSConstants.READ_TIMEOUT);
    sock.setKeepAlive(true);//from ww  w  . j  a va 2 s.  c om
    // sendRequest
    DataOutputStream out = new DataOutputStream(sock.getOutputStream());
    out.writeShort(FSConstants.DATA_TRANSFER_VERSION);
    out.writeByte(FSConstants.OP_COPY_BLOCK);
    out.writeLong(block.getBlockId());
    out.writeLong(block.getGenerationStamp());
    Text.writeString(out, source.getStorageID());
    destination.write(out);
    out.flush();
    // receiveResponse
    DataInputStream reply = new DataInputStream(sock.getInputStream());

    short status = reply.readShort();
    if (status == FSConstants.OP_STATUS_SUCCESS) {
        return true;
    }
    return false;
}

From source file:de.ailis.oneinstance.OneInstance.java

/**
 * Runs the client./* w  w w .  j  a va  2 s .  c o  m*/
 * 
 * @param socket
 *            The client socket.
 * @param args
 *            The command-line arguments.
 * @return True if server accepted the new instance, false if not.
 * @throws IOException
 *             When communication with the server fails.
 */
private boolean runClient(Socket socket, String[] args) throws IOException {
    // Send serialized command-line argument list to the server.
    ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
    out.writeObject(new File(".").getCanonicalFile());
    out.writeObject(args);
    out.flush();

    // Read response from server
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
    String response = in.readLine();

    // If response is "exit" then don't start new instance. Any other
    // reply will allow the new instance.
    return response == null || !response.equals("exit");
}

From source file:it.crs4.pydoop.mapreduce.pipes.BinaryProtocol.java

/**
 * Create a proxy object that will speak the binary protocol on a socket.
 * Upward messages are passed on the specified handler and downward
 * downward messages are public methods on this object.
 * @param sock The socket to communicate on.
 * @param handler The handler for the received messages.
 * @param key The object to read keys into.
 * @param value The object to read values into.
 * @param config The job's configuration
 * @throws IOException//w  w w  .  jav  a  2s  .c o  m
 */
public BinaryProtocol(Socket sock, UpwardProtocol<K2, V2> handler, K2 key, V2 value, Configuration config)
        throws IOException {
    OutputStream raw = sock.getOutputStream();
    // If we are debugging, save a copy of the downlink commands to a file
    if (Submitter.getKeepCommandFile(config)) {
        raw = new TeeOutputStream("downlink.data", raw);
    }
    stream = new DataOutputStream(new BufferedOutputStream(raw, BUFFER_SIZE));
    uplink = new UplinkReaderThread<K2, V2>(sock.getInputStream(), handler, key, value);
    uplink.setName("pipe-uplink-handler");
    uplink.start();
}

From source file:org.apache.hadoop.dfs.TestDataTransferProtocol.java

private void sendRecvData(String testDescription, boolean eofExpected) throws IOException {
    /* Opens a socket to datanode
     * sends the data in sendBuf./*w  w w .  j  a  v a  2s  .co  m*/
     * If there is data in expectedBuf, expects to receive the data
     *     from datanode that matches expectedBuf.
     * If there is an exception while recieving, throws it
     *     only if exceptionExcepted is false.
     */

    Socket sock = null;
    try {

        if (testDescription != null) {
            LOG.info("Testing : " + testDescription);
        }
        sock = new Socket();
        sock.connect(dnAddr, FSConstants.READ_TIMEOUT);
        sock.setSoTimeout(FSConstants.READ_TIMEOUT);

        OutputStream out = sock.getOutputStream();
        // Should we excuse 
        byte[] retBuf = new byte[recvBuf.size()];

        DataInputStream in = new DataInputStream(sock.getInputStream());
        out.write(sendBuf.toByteArray());
        try {
            in.readFully(retBuf);
        } catch (EOFException eof) {
            if (eofExpected) {
                LOG.info("Got EOF as expected.");
                return;
            }
            throw eof;
        }
        for (int i = 0; i < retBuf.length; i++) {
            System.out.print(retBuf[i]);
        }
        System.out.println(":");

        if (eofExpected) {
            throw new IOException("Did not recieve IOException when an exception "
                    + "is expected while reading from " + datanode.getName());
        }

        byte[] needed = recvBuf.toByteArray();
        for (int i = 0; i < retBuf.length; i++) {
            System.out.print(retBuf[i]);
            assertEquals("checking byte[" + i + "]", needed[i], retBuf[i]);
        }
    } finally {
        IOUtils.closeSocket(sock);
    }
}