Java Socket Read readData(Socket connId, byte[] dataRead, int nchar)

Here you can find the source of readData(Socket connId, byte[] dataRead, int nchar)

Description

Reads nchar from a given sockets, blocks on read untill nchar are read of conenction has error bRead returns the bytes read

License

Open Source License

Parameter

Parameter Description
connId a Socket
dataRead a byte[]
nchar an int

Exception

Parameter Description
IOException an exception

Return

an int

Declaration

static int readData(Socket connId, byte[] dataRead, int nchar)
        throws IOException 

Method Source Code

//package com.java2s;
import java.io.IOException;
import java.io.InputStream;

import java.net.Socket;
import java.util.Date;

public class Main {
    /**/*from   www.java  2 s.c o  m*/
     * Reads nchar from a given sockets, blocks on read untill nchar are read of conenction has error
     * bRead returns the bytes read
     *
     * @param    connId              a  Socket
     * @param    dataRead            a  byte[]
     * @param    nchar               an int
     *
     * @return   an int
     *
     * @throws   IOException
     *
     */
    static int readData(Socket connId, byte[] dataRead, int nchar)
            throws IOException {
        InputStream input;
        input = connId.getInputStream();

        int nread = 0;
        int startTime = (int) (new Date().getTime());
        do {
            if (input.available() != 0) {
                nread += input.read(dataRead, nread, nchar - nread);
                startTime = (int) (new Date().getTime());
            } else {
                int nowTime = (int) (new Date().getTime());
                if ((int) (nowTime - startTime) > 2000)
                    break;
            }
        } while (nread != nchar);

        return nread;
    }
}

Related

  1. getInputStreamFromSocket(final Socket socket)
  2. getPrintWriter(Socket s)
  3. getPrintWriterFromOutputStream(Socket socket)
  4. getResponse(Socket socket)
  5. readBytesIntoSocket(Socket socket)
  6. readMsg(Socket s)