views:

848

answers:

1

I am writing a quick server to test an application. If i close the socket on the other end it does not throw and exceptions that the socket is closed. I keeps writing 100mb of random data( what it is suppose to do). How can i detect if the other end closed connection?

import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.ServerSocket;
import java.util.Random;

public class server {

public static void main(String [ ] args){

int size = 1048576 * 100;

String response ="HTTP/1.0 200 OK\n" +
    "Server: server\n" +
    // "Date: Sun, 05 Apr 2009 04:40:08 GMT\n" +
    // "Last-Modified: Tue, 23 May 2006 22:18:19 GMT\n" +
    "Content-Type: application/zip\n" +
    "Content-Length: " + size + " \n" +
    "Connection: keep-alive\n";

try{
    ServerSocket serverSocket = new ServerSocket(4444);

    while(true){

 System.out.println( "Listenning..." );
 Socket clientSocket = serverSocket.accept();

 PrintWriter out = 
     new PrintWriter(clientSocket.getOutputStream(), true);
 BufferedReader in = new BufferedReader
     (new InputStreamReader( clientSocket.getInputStream()));
 String inputLine, outputLine;

 System.out.println("-----------Request-----------" );
 while ((inputLine = in.readLine()) != null) { 
     if (inputLine.equals("") == true )
  break;
     System.out.println( inputLine );
 }

 System.out.println("-----------Response-----------" );
 System.out.println( response );
 out.print(response);
 out.print("\r\n");

     //waits for the whole for to finish no exceptions are thrown
 Random rand = new Random();
 for( int i=0 ; i< size ;i++){
     int randnum = rand.nextInt(9);
     out.print( randnum );
 }

 //out.println("test");

 out.close();
 in.close();
    }

}catch( Exception e ) { 
    System.out.println( e.toString() );
}        
}

}

+4  A: 

The PrintWriter class ignores exceptions thrown by the underlying output stream. As stated in the documentation, you need to actively check it for errors.

You might consider using the Formatter class instead of PrintWriter. It will help you with the formatting of text like PrintStream and PrintWriter do (and a lot more), and will also pass along exceptions from the underlying Appendable (which should be an OutputStreamWriter in this case).

erickson