0

I am doing socket programming. I have two files called Server.java and client.java. Both programs were running successfully and successfully sending data to each other. Yesterday I added the following lines to client.java file:

     //old line
     out.writeUTF(dbdata); //dbdata was written successfully and sent to the server program
     try
     {
          //my socket connection object name is sock
            String data1="1000";
            System.out.println(data1);
            out.writeUTF(data1);   this line causes the error
     }

     catch(Exception e)
     {
            System.out.println("Exception :: "+e);
     }

When the line out.writeUTF(data1) is executed and catch catches it and shows the exception as BROKEN PIPE.

The contents of server.java which reads data1 is given below:

     String data1;
     try
     {
            data1=in.readUTF();
     }
     catch(Exception e)
     {
            System.out.println("Server Exception :: "+e);
     }

I also checked if connection is open with isConnected() before out.writeUTF(data1) and after the exception occurs in the catch I executed isConnected(). Both the times it showed True only.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
user1673627
  • 271
  • 3
  • 6
  • 13
  • The exception is ----- java.net.SocketException: Broken pipe – user1673627 Sep 22 '12 at 06:05
  • isConnected() doesn't tell you whether the connection is still up. It tells you whether this socket was ever connected. It's not the same thing. – user207421 Sep 22 '12 at 10:04
  • Try this useful link and don't forget to call `out.flush()` to save and `out.close()`. http://stackoverflow.com/questions/1053467/how-do-i-save-a-string-to-a-text-file-using-java – Hesham Magdy Sep 22 '12 at 06:06

2 Answers2

1

'Broken pipe' means you have written to a connection that has already been closed by the other end. In other words, an application protocol error. The mitigation is not to do it, either by fixing this end so it doesn't write unwanted data, or fixing the other end so it reads all the wanted data.

user207421
  • 305,947
  • 44
  • 307
  • 483
1

@EJP is right. The exception means that the socket was closed before the write call could complete, and possibly before it started. There is no way of knowing how much of the data was delivered to the other end.

The other part of the puzzle is why isConnected() is returning true. That is explained by the javadoc which says:

"Note: Closing a socket doesn't clear its connection state, which means this method will return true for a closed socket (see isClosed()) if it was successfuly connected prior to being closed."

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216