2

I have a socket program which is sending text data via PrintWriter(out.write(String str)), on the other side BufferedReader(in.readLine()) is receiving this.

I want to secure my program with some kind 'timeout' if one of clients breaks the connection, but I tested it and during work, when client will be turned off, server is still sending data and there is no interruption nor socket closing.

Same for client, I want to break connection and display info for example "server is not working". How I can handle this ?

// Server
out = new PrintWriter( sock.getOutputStream());
while( true ) {
   this.out.write("Hello");
   this.out.flush();
}

// Client
in = new BufferedReader( new InputStreamReader( sock.getInputStream()));
while (true) {
   in.readLine();
}
1
  • Set a read timeout on the socket. Commented Mar 30, 2021 at 22:57

2 Answers 2

2

I think your problem is PrintWriter. See its documentation:

Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError().

use BufferedWriter instead.

Note that java.util.Scanner has the same issue (in case you are using it on the server side)

Sign up to request clarification or add additional context in comments.

Comments

1

I just checked and PrintWriter.checkError() method helped me with my issue. When client broke connection, method returned true. As says description: Flushes the stream if it's not closed and checks its error state.

// Server
this.out = new PrintWriter(sock.getOutputStream());
while (true) {
   this.out.write("Hello");
   this.out.flush();
   if(this.out.checkError()){
      //...
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.