10

I have a thread that reads characters from a Buffered reader (created from a socket as follows):

inputStream = new BufferedReader(new InputStreamReader(clientSock.getInputStream()));

This code works only one time. For example, if a client connects and sends this: "This is a test" and "This is another test", the host output is:

 Reading from stream:
 Chars read from stream: 16
 This is a test

 Reading from stream:

Note that the program does not receive "This is another test", because it is stuck on reading the stream. Is there any way of dealing with this without reducing the buffer size? This is the code for the thread:

public void run() {
        boolean dataRecieved = false;
        char[] inputChars = new char[1024];
        int charsRead = 0;

        while (!stopNow) {

            try {
                Thread.sleep(getDataDelay);

                //Read 1024 characters. Note: This will pause the thread when stream is empty.
                System.out.println("Reading from stream:");
                charsRead =  inputStream.read(inputChars); //<< THIS LINE IS PAUSING THE THREAD!> 


                if ((charsRead =  inputStream.read(inputChars)) != -1)
                {
                    System.out.println("Chars read from stream: " + charsRead);  
                    System.out.println(inputChars);
                    System.out.flush();
                }


            } catch (IOException e) {
                System.out.println("IOException");
                //TODO: CLIENT HAS DISCONNECTED...
            } catch (InterruptedException e) {
                System.out.println("Interrupted");
                // Sleep was interrupted.
            } 

        }

    }

Code for client/sender (not my code):

public static void main(String[] args) throws IOException {
        // <<<<<<<<<<< CLIENT >>>>>>>>>>>>>>>

        Socket sock = new Socket("127.0.0.1", 3000);
        // reading from keyboard (keyRead object)
        BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
        // sending to client (pwrite object)
        OutputStream ostream = sock.getOutputStream(); 
        PrintWriter pwrite = new PrintWriter(ostream, true);

        // receiving from server ( receiveRead  object)
        InputStream istream = sock.getInputStream();
        BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));

        System.out.println("Start the chitchat, type and press Enter key");

        String receiveMessage, sendMessage;               
        while(true)
        {
            sendMessage = keyRead.readLine();     // keyboard reading
            pwrite.println(sendMessage);       // sending to server
            System.out.flush();         // flush the data

            if((receiveMessage = receiveRead.readLine()) != null) //receive from server
            {
                System.out.println(receiveMessage); // displaying at DOS prompt
            }         
        }               
    }          
11
  • Make sure that the other sends something.
    – khachik
    Jun 13, 2011 at 8:26
  • That link does not help me. I am already using threads. The problem is, I cannot receive data from the client more than one time.
    – David
    Jun 13, 2011 at 8:30
  • have you tried flushing the output from the sender?
    – sinan
    Jun 13, 2011 at 8:54
  • @bs0d1 I'll include the code for the sender too then.
    – David
    Jun 13, 2011 at 8:57

5 Answers 5

13

java.io.InputStream.read() is a blocking call, which means if no data is available the thread halts until data becomes available.

For non-blocking I/O, use classes from the java.nio package.

0
3

Your "sender" is waiting to receive data back from the "receiver", and this is where the code waits indefinitely. Is the receiver supposed to be sending a response when it gets a message?

0
0

Implement a protocol where you send the length of your data in your headers so the server/client knows how much data to expect.

0
0
Socket socket;

// Assuming socket is connected and not null

if(socket != null){
    if(socket.getInputStream().available() > 0){
        byte[] buffer;
        buffer = new byte[socket.getInputStream().available];
        socket.getInputStream().read(buffer);

        // Your code here to deal with buffer.

    }
}

If you want to write to the socket,

OutputStream mmOutStream;
mmOutStream = socket.getOutputStream();

public void write(byte[] buffer) {
    try {
        mmOutStream.write(buffer);
    } catch (IOException e) {
        Log.e(TAG, "Exception during write ", e);
    }
}
1
  • This usage of available() is specifically warned against in the Javadoc.
    – user207421
    Mar 14 at 0:35
-1

You have to create ServerSocket That listen to client in every loop.

ServerSocket socket = new ServerSocket(3000);

Here is my run() method that will wait for client Socket every time

public void run(){
        boolean dataRecieved = false;
        char[] inputChars = new char[1024];
        int charsRead = 0;

        while (!stopNow) {
            try {
                System.out.println("Listen To Clients:");

                // The ServerSocket has to listen the client each time.
                InputStreamReader isr = new InputStreamReader( socket.accept().getInputStream() );
                inputStream = new BufferedReader( isr );

                //Read 1024 characters. Note: This will pause the thread when stream is empty.
                System.out.println("Reading from stream:");

                if ((charsRead =  inputStream.read(inputChars)) != -1)
                {
                    System.out.println("Chars read from stream: " + charsRead);  
                    System.out.println(inputChars);
                    System.out.flush();
                }
            } 
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        }
    }

You have another minor mistake that halts the code and remove the line

charsRead =  inputStream.read(inputChars); //<< THIS LINE IS PAUSING THE THREAD!>

Because this line is moved in an if statement.

1
  • It is obvious from the fact that his server I/O code is already executing that he already has a ServerSocket. Your final comment is incomprehensible.
    – user207421
    Jun 29, 2015 at 2:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.