未检测到Java Socket关闭

时间:2009-04-10 20:57:56

标签: java sockets connection

我正在编写一个快速服务器来测试应用程序。如果我在客户端关闭套接字,它不会抛出套接字关闭的异常。我一直在写100mb的随机数据(这是假设要做的)。如何检测客户端是否已关闭连接?

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() );
}           
}
}

1 个答案:

答案 0 :(得分:5)

PrintWriter类忽略基础输出流抛出的异常。如文档中所述,您需要积极check it for errors

您可以考虑使用Formatter类而不是PrintWriter。它会帮助您格式化PrintStreamPrintWriter等文本(以及更多内容),并且还会传递来自基础Appendable的异常(应该是{{} 1}}在这种情况下)。