Can someone explain what exactly these sentences do? :)
BufferedReader in = new BufferedReader(
client.getInputStream( ) ) );
PrintWriter out = new PrintWriter(
client.getOutputStream( ) ) ),true );
Look up the constructors for all the used classes and it becomes clear; the IO system uses the 'decorator' or 'wrapper' pattern, e.g your client can deliver an InputStream, when you wrap that in an InputStreamReader you have a Reader, when you wrap that in a BufferedReader you have a BufferedReader. Similar reasoning applies to the wrapping of the output.
Originally Posted by Nerijus
thanks :) and can you explain why client read message from server is this way:
and send message to server like that:
What is the difference between these methods:
OutputStream outputStream = client.getOutputStream();
InputStream inputStream = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
byte msg = line.getBytes();
int bytesRead = inputStream.read(info);
byte temp = Arrays.copyOfRange(info, 0, bytesRead);
System.out.println("\nRecieved "+ bytesRead +"bytes");
System.out.println("Recieved "+ new String(temp));
The difference is this:
OutputStream (or Writer) write into the stream RIGHT AWAY. So if you do
this will result in 3 separate writes into the output stream. The time it takes to write into the stream is SETUP + CONSTANT * message size. In this case, the total time is 3 * SETUP + CONSTANT * total message size.
Now suppose you were using BufferedOutputStream (or BufferedWriter). when you call
it writes into some buffer instead of the stream. The actual writing into the stream will happen later, when the BufferedWriter decided the buffer is large enough so it makes sense to write it. So in effect, it combines multiple writes into one. The time you spend with this approach is SETUP + CONSTANT * total message size, which of course is better.
One problem you occasionally run into is that BufferedWriter.write() doesn't actually send anything, and you aren't receiving anything at the other end. use BufferedWriter.flush() to force it to actually perform the writing.