ObjectOutputStream不刷新

ObjectOutputStream不刷新

本文介绍了套接字上的Java ObjectOutputStream不刷新()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java编写的网络应用程序,使用Sockets顶部的ObjectOutputStream和ObjectInputStream交换消息.我的代码如下:

I'm working on a network app written in Java, using ObjectOutputStream and ObjectInputStream on top of Sockets to exchange messages. My code looks like this:

发件人:

ObjectOutputStream out;
ObjectInputStream in;
try{
     Socket socket=new Socket(address, port);
     socket.setSoLinger(true, socketLingerTime);
     out=new ObjectOutputStream(socket.getOutputStream());
     out.writeObject(message);
     out.flush();
     out.close();
}catch (variousExceptions)...

接收器:

Object incoming;
try{
    incoming=myObjectInputStream.readObject();
}catch (SocketException socketError)
{
    if (socketError.getMessage().equals("Connection reset"))
    {
        //this is the exception I get
    }
}

有时消息会通过,但是有时我会收到标记的异常而不是对象.冲洗不是强制将消息传递到另一侧吗?我是否以某种方式不正确地使用了该功能?还是这是底层Java/OS网络代码中的某种错误?

Sometimes the message goes through ok, but other times I get the marked exception instead of an object. Isn't flush supposed to force the message through to the other side? Am I somehow using the function incorrectly? Or is this some sort of bug in the underlying Java/OS network code?

谢谢!

更新:

我对此进行了更多探查,它似乎仅在系统资源受到某种负担时才发生.我无法在VirtualBox外部复制它,但这可能只是因为VirtualBox最初没有太多资源.当我进一步调查时,我将使该问题保持最新状态.

I've done some more snooping on this, and it seems to only happen when the system's resources are being taxed by something. I've not been able to replicate it outside the VirtualBox, but that could just be because the VirtualBox doesn't have many resources to begin with. I'll keep this question updated as I look into it further.

推荐答案

事实证明,问题是由Nagle的算法引起的;输出缓冲区在操作系统内,因此不受刷新的影响.解决方案是使用Socket.setTcpNoDelay(true)关闭Nagle的算法,并使用BufferedOutputStream在用户级别缓冲消息.

It turns out the issue was caused by Nagle's Algorithm; the output buffer is within the OS, so it wasn't affected by flush. The solution is to turn Nagle's Algorithm off using Socket.setTcpNoDelay(true), and buffer messages at the user level using BufferedOutputStream.

这篇关于套接字上的Java ObjectOutputStream不刷新()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 03:00