File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes I/O client server excercise Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "I/O client server excercise" Watch "I/O client server excercise" New topic

I/O client server excercise

Simone Sarigu

Joined: May 09, 2012
Posts: 7
this is the excercise I'm trying to do:

write to java classes client and server with these features:
Server: Accept messages from the client (sent as lines of text) and returns them to the client numbering them.
Client: sends messages in lines of text to the server.
The connection is closed with the string "bye".
<the client sends>"Hello server";
<the client receives> "Message 1: Hello server!"
<the client sends> "What a beautiful day!"
<the client receive> "Message 2: What a beautiful day!"

The problem is that after the second message sent the client ends with an exception:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(
at java.lang.AbstractStringBuilder.expandCapacity(
at java.lang.AbstractStringBuilder.ensureCapacityInternal(
at java.lang.AbstractStringBuilder.append(
at java.lang.StringBuffer.append(
at clientserver.Client.receive(
at clientserver.Client.send(
at clientserver.Client.<init>(
at clientserver.Client.main(
Java Result: 1

I'm sure it's a issue of how I wrote the receive method in the client class or the send method in the server class.
If I comment these methods the server receives messages from the client and ends without any problems.

These are the classes:


Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

You have nested loops:

So you get a message, and as long as that one single message that you got (which never changes) is not "bye", you're sending back a response. A single message produces infinitely many copies of the same resopnse.

The send() method does not need a loop. Your loop should be

but what you have is

Once you get into that inner loop, you can never get out.
Simone Sarigu

Joined: May 09, 2012
Posts: 7
Thank you very much
I wouldn't ever came out of that mess but I'm still doing something wrong

I'm proceeding by trial and error. I've rewritten the send method in different ways.
I think this is the closest at the result:

In this way the client receives back the first message and the server throws an IOException: socket closed
at Method)
at sun.nio.cs.StreamDecoder.readBytes(
at sun.nio.cs.StreamDecoder.implRead(
at clientserver.Server.receive( ----------------------> messaggio = bfIn.readLine();
at clientserver.Server.<init>(
at clientserver.Server.main(

Why that line? I'd expected this pw.close();

Simone Sarigu

Joined: May 09, 2012
Posts: 7
no one?
I agree. Here's the link:
subject: I/O client server excercise
It's not a secret anymore!