java - 在java中写入套接字时数据去哪里了?

标签 java sockets

假设我有以下代码,它设置了一个 Socket 和一个用于读取和写入套接字的输入和输出流。

toMonitor = new Socket(sd.m_sMonName, sd.m_iMonPort);
out = new PrintWriter(toMonitor.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(toMonitor.getInputStream()));

还说我有下面称为 SendIt 的方法,它将一个字符串写入 Sockets 输出流
public void SendIt (String message) throws IOException 
{
    try 
    {        
        newStatus("MessageParser [SendIt]: sent:\n\t" + message, true);

        out.println(message);
        if (out.checkError() == true) 
            throw (new IOException());
        out.flush();
        if (out.checkError() == true) 
            throw (new IOException());
    } 
    catch (IOException e) {} //Bubble the Exception upwards
}

当我调用 out.println(message);上面,该消息是否会位于缓冲区中,直到套接字的另一端读取它?
- 我认为底层编写器对象会将其分解为字节,将其发送到套接字输出流,在那里它被组装成数据包并发送出去,从而在写入时清除缓冲区?

它会坐在那里直到我调用out.flush() ?

是否 out.flush()总是清除缓冲区,或者有什么东西可以留在里面,不知何故..?

编辑:

我目前正在使用 Netbeans 作为我的 IDE,是否可以在程序运行时实时查看输出缓冲区的实际值?

最佳答案

When I call out.println(message); above, will that message sit in the buffer until the other end of the socket reads it?



不,它会转到您的网络接口(interface),一旦缓冲区已满或您刷新 io 写入器/流,它就会将其传输到远程节点。如果没有连接到远程节点,则套接字关闭,一般不会接受写入并抛出异常(只要 knows )

Will it sit there until I call out.flush()?



它可能会也可能不会。请注意,您在此处刷新的缓冲区是 PrintWriter 的缓冲区,而不是网络套接字的缓冲区。因此,out.flush()不保证传输,尽管如果连接仍然正常,接下来通常会发生这种情况。作为 Java reference状态:

(...) flushing the stream guarantees only that bytes previously written to the stream are passed to the operating system for writing; it does not guarantee that they are actually written to a physical device such as a disk drive.



最后,你的最后一个问题:

Does out.flush() ALWAYS clear the buffer, or could something stay in there, somehow..?



不,根据引用资料,任何 io writer 或流缓冲区中都不会保留任何内容:

one flush() invocation will flush all the buffers in a chain of Writers and OutputStreams.

关于java - 在java中写入套接字时数据去哪里了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21199439/

相关文章:

java - Android上传图片进度条

java - 如何使用 Java 从 html 源代码中解析特定信息

ruby - Ruby 套接字编程中的标准套接字超时(秒)是多少?

c - 如何用C语言在Unix Socket上禁用Nagle算法?

java - 使用蓝牙适配器将字符串从 PC 发送到 Android 应用程序

java - 如何使用 try 和资源将 while 循环放入线程中?

java - 将二维数组保存到磁盘文件

javascript - 我如何从服务器端java代码调用Javascript函数并向其传递数据?

java - Netty 4 从客户端创建多个连接

sockets - Python3 从 self.connect(('badhost' ,6667) 时捕获错误