首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >套接字打开管道,但不关闭管道

套接字打开管道,但不关闭管道
EN

Stack Overflow用户
提问于 2015-12-10 12:28:03
回答 1查看 586关注 0票数 1

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

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

下面是我的程序:

代码语言:javascript
运行
复制
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) {}
    }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2015-12-23 06:42:37

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

)。

是的,在socketTimeout被设置为非零值后,SocketInputStream开始在readLine()内部使用非阻塞读取,并且可以(如果输入还没有出现在套接字中)打开每个读取线程最多两个管道。

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

您不必这样做,在这种情况下,管道将在下一次GC之后关闭,而选择器(保存文件描述符in )将由sun.misc.Cleaner关闭。Cleaner类基于PhantomReference,它的清理是在ReferenceHandler线程中执行的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34193690

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档