This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes What exactly is Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What exactly is "line flushing" and how does it relate to the following code?" Watch "What exactly is "line flushing" and how does it relate to the following code?" New topic
Author

What exactly is "line flushing" and how does it relate to the following code?

Tarek Khojah
Ranch Hand

Joined: Jul 21, 2007
Posts: 58
I don't want to waste your time, this isn't really THAT important. My code wasn't working and now it does because of one simple change. But I don't understand what that change does. So the following is about that:

I've been struggling with writing my own (simpler) version of a client/server "program" using THIS

Very simple really, just something that would say "hi" and "hello" back and forth.

When I tried the code in the example, it worked fine. But when I wrote my own code, both the client and server programs would run, but nothing happens! When I come to close either program, I'll get an error at the while loop of the other program (Seems like both programs are just infinitely looping there).

Turns out I was omitting the bolded part of the following line when creating a PrintWriter object:

out = new PrintWriter(socket.getOutputStream(), true);

So now the code works, but why? I looked into the API, and it mentions "line flushing", but what is that exactly? I'm assuming it means erasing the contents of the writer every time I write something new! If that's the case shouldn't my code have gone the while loop at least once before getting some sort of error?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14193
    
  20

PrintWriter buffers the data that you write to it. After you have written a certain amount of data, or if you print a newline, or if you call flush(), it sends out the data that it has in its buffer.

It does this because it is much more efficient to send packets of data than to send the data byte by byte.

By setting the second parameter of the constructor to true, you tell PrintWriter to send out its data immediately, without buffering it.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
 
GeeCON Prague 2014
 
subject: What exactly is "line flushing" and how does it relate to the following code?