Closing BufferedWriter Stream closes Socket

B

Brett Everton

Hello,

I have a simple client server application, where the server creates a
socket and listens for a client to connect. Once connected, the server
receives communication from the client via

socketConnection = socketServer.accept();

dataIn = new DataInputStream(socketConnection.getInputStream());

and the server sends out data to the client with

bufferOut = new BufferedWriter(new
OutputStreamWriter(socketConnection.getOutputStream()));

My problem is the client does not detect the end of the stream with

while ((line = bufferIn.readLine()) != null) {

I have read that to cause an EOF in a stream the stream must be
closed, flushing the stream etc is not enough.

My problem is that when i close the stream ( bufferOut ) on the server
side, the client detects the end of the stream but the
socketConnection closes also on the server side.

Can someone explain why I am losing my socket connection just by
closing my bufferedwriter stream? Or let me know a better way to go
about it.

Thanks in advance
Brett
 
G

Gordon Beaton

My problem is the client does not detect the end of the stream with

while ((line = bufferIn.readLine()) != null) {

I have read that to cause an EOF in a stream the stream must be
closed, flushing the stream etc is not enough.

Whenever you close any stream, all underlying streams and the socket
(or file, or whatever) are also closed. You can't do anything about
that.

If you want to indicate the end of a "message" without closing the
stream, you need to look for something other than EOF at the receiving
end.

Your application needs a clearer definition of a message. Typically
messages are sent using some variation of the following:

- send a special delimiter after each message. The delimiter can't
occur unescaped within the message itself
- send the message length, followed by the message contents

Since you seem to be using a text-based protocol, a suitable delimiter
might be something like a newline, or an empty line if your messages
can be more than one line.

/gordon
 
B

Brett Everton

Thank you for you help

I ended up sending '-1' at the end of the stream on the server side
and instead of using

String line;
while ((line = bufferIn.readLine()) != null) {

on the client side. I used

line = bufferIn.readLine();
while (!line.matches("-1")) { // determine if end of stream
line = bufferIn.readLine();

This seems to work well.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top