插座打开管道但不关闭它

时间:2015-12-10 04:28:03

标签: java linux sockets pipe bufferedreader

我正在监听套接字并使用了readLine()函数。 如果我看到程序打开的文件描述符的数量,我看到当我调用readLine()函数时,会打开两个文件描述符(管道)。 (可以在/ proc // fd中看到)

如果发生套接字超时异常,即使关闭缓冲读取器,管道仍保持打开状态。 我该如何关闭?

这是我的计划:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.SocketChannel;
import java.util.StringTokenizer;

// Test case code for file descriptor leak.
// The following should produce somewhere near 150 sockets in CLOSE_WAIT state.
// The problem appears to be in   sun.nio.ch.SocketAdapter.SocketInputStream.read(ByteBuffer);

public class TestClose implements Runnable {

public static final String SMTP_HOSTNAME = "10.10.10.59";

    public void run()
    {
    InetSocketAddress sockAddr = new InetSocketAddress(SMTP_HOSTNAME, 5269);
            SocketChannel sChannel = null;
            Socket socket = null;
            String result = null;
             BufferedReader lineRdr = null;
             InputStreamReader is  = null;
            try
            {
                    sChannel = SocketChannel.open();
                    sChannel.socket().connect(sockAddr);


                    sChannel.socket().setSoTimeout(20000);
                    socket = sChannel.socket();

                    is = new InputStreamReader(socket.getInputStream());
                   lineRdr = new BufferedReader(is);



                    do
                    {
            // before performing the first readline the channel is unregistered
                            System.err.println("before first readline: isOpen = "+sChannel.isOpen()+" isRegistered="+sChannel.isRegistered());                                

                            result = lineRdr.readLine();                            

                            System.err.println("<- "+result);

            // after performing it is registered.
                            System.err.println("after first readline: isOpen = "+sChannel.isOpen()+" isRegistered="+sChannel.isRegistered());

                    } while(result != null && result.length() > 0 && result.matches("^[1-5][0-9]{2}-"));

                    if(result == null || result.length() == 0)
                    {
                            System.err.println("Received truncated response from SMTP server " + sockAddr.getHostName());
                            return;
                    }

                    // Tokenize the last line result
                    //
                    StringTokenizer t = new StringTokenizer(result);
                    int rc = Integer.parseInt(t.nextToken());
                    if(rc != 220) return;

                    //
                    // Send the QUIT command causing the server side to close its end of the connection
                    //
                    String cmd = "QUIT\r\n";
                    socket.getOutputStream().write(cmd.getBytes());
                    System.err.println("-> "+cmd);
                    do
                    {
                            result = lineRdr.readLine();
                            System.err.println("<- "+result);
                    } while(result != null && result.length() > 0 && result.matches("^[1-5][0-9]{2}-"));

                    if(result == null || result.length() == 0)
                    {
                            System.err.println("Received truncated response from SMTP server " + sockAddr.getHostName());
                            return;
                    }

            }
    catch (Exception e) {
        System.out.println("result "+result);
        e.printStackTrace();
    }
            finally
            {
        try {

                //socket.getInputStream().close();
               lineRdr.close();
               lineRdr = null;
               is.close();
            is = null;

               System.err.println("before close: isOpen = "+sChannel.isOpen()+" isRegistered="+sChannel.isRegistered());

            System.err.println("Closing SMTP socket channel "+sChannel);
            System.err.println("channel.socket().isConnected = "+ sChannel.socket().isConnected());
             System.err.println("channel.socket().isclose = "+ sChannel.socket().isClosed());
             System.err.println("channel.socket().isConnected = "+ sChannel.socket().isConnected());
            if (sChannel != null) {
                if(sChannel.socket().isClosed()== false){
                            sChannel.socket().shutdownOutput();
                     sChannel.socket().close();
                    }
                   // sChannel.shutdownOutput();
                    sChannel.close();
                    System.err.println("Closed SMTP socket channel "+sChannel);

                // The socket is still connected here.
                    System.err.println("channel.socket().isConnected = "+sChannel.socket().isConnected());
                    System.err.println("channel.socket().isclose = "+ sChannel.socket().isClosed());
            }
        }
        catch (Exception e) {
           System.err.println("Exception on close:");
           e.printStackTrace();
        }
            }

            return;
    }


    public static void main(String[] args) {
    TestClose test = new TestClose();
    while(true) {
    for(int i = 0; i < 1; i++) {
     // this bug seems only to appear if different threads are reading the channels
            Thread thread = new Thread(test);
        thread.start();
        try {thread.join(); } catch(InterruptedException e) {   }
    }

    System.err.println("Going to sleep.... run netstat -an | grep CLOSE_WAIT ");

            try { Thread.sleep(10000); } catch(InterruptedException e) {}
    }
    }
}

1 个答案:

答案 0 :(得分:1)

  

我看到readLine()函数打开了两个文件描述符   (管道)。

是的,在socketTimeout设置为非零值后,SocketInputStream开始在readLine()内使用非阻塞读取,并且可以(如果输入尚未存在于套接字中)打开最多两个管道阅读帖子。

  

如果发生套接字超时异常,即使在关闭Buffered之后也是如此   读者,管道仍然打开。我该如何关闭?

你不必,在你的情况下,管道将在下一个GC之后关闭,当选择器(其中包含文件描述符ID)将被sun.misc.Cleaner关闭时。 Cleaner类基于PhantomReference,其清理在ReferenceHandler线程中执行。