简体   繁体   English

我可以正确关闭这个插座吗?

[英]Am i closing this socket correctly?

For the most part, it works, however sometimes it doesn't, this code is ment to close the socket only if(input.equals("Done")){ , am i closing it correctly? 在大多数情况下,它可以工作,但是有时却不起作用,该代码仅if(input.equals("Done")){时才关闭套接字,我可以正确关闭吗? , it seems to me, from the code that i'm trying to close it regardless? ,在我看来,无论我尝试关闭它的代码是什么? Can anyone confirm or correct it from me? 谁能向我确认或更正?

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

First of all, you're disposing your object inside while loop, so they will be disposed no matter the second message is received (you're skipping the first with line just before while loop). 首先,您将对象放置在 while循环内,因此无论接收到第二条消息,它们都将被放置(在while循环之前,您将第一个行跳过了)。 If the second message by any chance will be DONE, then you're going out of loop without any socket disposial, so they're still inside your memory. 如果第二条消息有可能被完成,那么您将退出循环而没有任何套接字处置,因此它们仍在您的内存中。 And, as many pointed in comments, you may have problem, if any of your objects throws exceptions. 而且,正如注释中指出的那样,如果您的任何对象引发异常,则可能会遇到问题。 The correct version for this app would be: 此应用程序的正确版本为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM