使用流关闭套接字

Closing a Socket with Streams

我的以下问题非常简单。

这是我的代码:

public class Protocol implements Runnable {

    private SSLSocket socket = null;
    private InputStream is = null;
    private OutputStream os = null;

    ...

    public Protocol(Socket s) {
        socket = (SSLSocket)s;
        is = socket.getInputStream();
        os = socket.getOutputStream();
    }


    @Override
    public void run() {

        ...
        ping();
        socket.close();
        ...
    }


    public void ping() {

        BufferedWriter writer;
        try {
            writer = new BufferedWriter(new OutputStreamWriter(os));
            writer.write("OK");
        } 
        catch (IOException e) { System.out.println("ERROR: " + e.getLocalizedMessage()); }
        finally { writer = null; }
    }

我知道我没有包含很多源代码,但这应该足以回答问题。如您所见,在 "ping" 方法中,我创建了一个 BufferedWriter,用于将 "OK" 字符串写入远程源。稍后,我 close Socket.

所以我的简单问题是 - 据我了解,因为我 close 套接字,链应该是这样的:

Close socket ----> closes 和 os ----> closes作家

因此,通过 closing Socket,我也 closing 并允许 GC 释放 BufferedWriter。我是理解正确还是做错了什么?对于我在其他方法(即 BufferedInputStream)中初始化的所有作者和读者来说都是这样吗?通过在方法结束时将这些变量设置为 null,我是否在帮助 GC 区分应该释放的内容?或者我不应该这样做?

谢谢!

From what I understand, since I close the socket, the chain should go like this:

Close socket ----> which closes is and os ----> closes writer

没有。 BufferedWriter 包裹在套接字输出流周围,但套接字不知道。它无法关闭它。

So, by closing the Socket, I am also closing and allowing the BufferedWriter to be freed by the GC.

没有也没有。 BufferedWriterping() returns 后立即可用于 GC,并且根本不会关闭。

Am I understanding this correctly

没有

or doing something wrong?

是的。您不应为每条消息创建一个新的 BufferedWriter。您应该在套接字的整个生命周期内使用同一个套接字,并关闭 it 而不是套接字。同样,在套接字的生命周期内,您应该只使用一个输入流或 Reader。否则您可能会丢失缓冲区中的数据。

Is this true for all writers and readers that I initialize in other methods (i.e. BufferedInputStream).

没有

And by setting these variables null at the end of the method, am I helping the GC to distinguish between what should be freed?

没有。你只是在浪费时间和 space。该方法无论如何都即将退出,所以它的所有局部变量都消失了。

Or should I not do this?

你不应该做任何事情。