DataOutputStream不刷新 [英] DataOutputStream not flushing

查看:167
本文介绍了DataOutputStream不刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java客户端,可以将UTF-8字符串发送到C#TCP-Server,我正在使用DataOutputStream发送字符串。代码如下所示:

I have a Java Client which sends UTF-8 strings to a C# TCP-Server, I'm using a DataOutputStream to send the strings. The code looks like this:

public void sendUTF8String(String ar) {
    if (socket.isConnected()) {
        try {
            dataOutputStream.write(ar.getBytes(Charset.forName("UTF-8")));
            dataOutputStream.flush();
        } catch (IOException e) {
            handleException(e);
        }
    }
}

问题是冲洗不会似乎工作不正确。如果我发送两个彼此靠近的字符串,则服务器仅会收到一条包含两个字符串的消息。如果我在两次调用之间执行Thread.sleep(1000),则整个工作正常,这显然不是解决方案。
我想念什么?

The problem is that flush doesn't seem to work right. If I send two Strings close to each other, the server receives only one message with both strings. The whole thing works if I do a Thread.sleep(1000) between calls, this is obviously not a solution. What am I missing?

推荐答案

flush()不保证数据包会被运送出去。您的TCP / IP堆栈可以自由捆绑数据,以实现最高效率。更糟糕的是,您与目的地之间可能还有许多其他TCP / IP堆栈,它们可以自由地执行相同的操作。

flush() doesn't guarantee that a data packet gets shipped off. Your TCP/IP stack is free to bundle your data for maximum efficiency. Worse, there are probably a bunch of other TCP/IP stacks between you and your destination, and they are free to do the same.

我认为您不应该依赖在数据包捆绑上。在数据中插入一个逻辑终止符/分隔符,您将很安全。

I think you shouldn't rely on packet bundling. Insert a logical terminator/divider in your data and you will be on the safe side.

这篇关于DataOutputStream不刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆