我正确地关闭了这个插座吗?

时间:2016-06-20 16:27:13

标签: java sockets serversocket

在大多数情况下,它有效,但有时它不起作用,此代码只关闭套接字if(input.equals("Done")){,我正确关闭它吗? ,在我看来,从我试图关闭它的代码无论如何?任何人都可以向我确认或更正吗?

Socket socket1;
int portNumber = 4445;
socket1 = new Socket(InetAddress.getLocalHost(), portNumber);
BufferedReader br = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
PrintWriter pw = new PrintWriter(socket1.getOutputStream(), true);

pw.println("Hello");
pw.println("Hello");
pw.println("Hello");
pw.println("Hello");

String input = br.readLine();
while ((input = br.readLine()) != null) {
    if(input.equals("Hi")){
        pw.println("Hello");
    }
    else  if(input.equals("Done")){
        break;
    }

    br.close();
    pw.close();
    socket1.close();
}

1 个答案:

答案 0 :(得分:0)

首先,您在循环中将对象放置在内部,因此无论收到第二条消息,它们都会被处理掉(您只是在线路上跳过第一条消息)在while循环之前)。如果第二条消息任何机会都将完成,那么您将在没有任何套接字处理的情况下退出循环,因此它们仍然在您的内存中。而且,正如许多人在评论中指出的那样,如果你的任何对象抛出异常,你可能会遇到问题。这个应用程序的正确版本是:

Socket socket1 = null;
int portNumber = 4445;
BufferedReader br = null;
PrintWriter pw = null;
try
{
    socket1 = new Socket(InetAddress.getLocalHost(), portNumber);
    br = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
    pw = new PrintWriter(socket1.getOutputStream(), true);

    pw.println("Hello");
    pw.println("Hello");
    pw.println("Hello");
    pw.println("Hello");

    String input = null;
    while ((input = br.readLine()) != null) {
        if(input.equals("Hi")){
            pw.println("Hello");
        }
        else  if(input.equals("Done")){
            break;
    }
}
finally
{
    if(br != null) br.close();
    if(pw != null) pw.close();
    if(socket1 != null) socket1.close();
}