0

I am creating a socket server for a school project. The client is written in C# so the ObjectInputStream object I have been using so far is not working.

I am now trying to use InputStreamReader. In this example, the while (true) loop is running at full throttle all the time. Using the ObjectInputStream it'd wait for an object to arrive.

How can I do this in a proper way?

private InputStreamReader inputStream;

@Override
public void run() {

    while (true) {

        try {

            // ObjectInputStream.read() waits for an object to arrive, 
            // so the execution is paused here

            int data;
            String string = new String();

            while ( (data = inputStream.read() ) != -1) {
                char thisChar = (char) data;
                string = string + thisChar;
            }


        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            break;
        }

    }

}
3
  • 1
    I'm pretty sure that inputStream.read() will block until data becomes available. It will return -1 if the stream is closed, and inputStream.ready() will tell you if it has bytes in its buffer or not. The only thing I really see missing from your code is a way for the thread to exit in a controlled manner. So what exactly is the problem? Commented Feb 19, 2014 at 14:52
  • 1
    Uhm, what are you reading exactly? Strings? In what encoding? You should use a Reader Commented Feb 19, 2014 at 14:53
  • is inputStream ever getting initialized? Commented Nov 24, 2014 at 16:10

1 Answer 1

1

Get rid of the outer loop. It's pointless. The inner loop will run until end of stream. After that, further iteration is futile. You're spinning at EOS.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice catch, I didn't even see the outer loop :/

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.