【问题标题】:Socket using BufferedOutputStream/BufferedInputStream receives bogus data random使用 BufferedOutputStream/BufferedInputStream 的套接字随机接收虚假数据
【发布时间】:2013-06-19 07:33:42
【问题描述】:

我有一个客户端/服务器应用程序,它使用 BufferedOutputStream / BufferedInputStream 发送/接收数据。通信协议如下:

  1. 发送部分:

    • 第一个字节是要执行的动作
    • 接下来的4个字节是消息的长度
    • 接下来的 x 个字节(x=消息长度)是消息本身
  2. 接收部分:

    • 读取第一个字节以获取操作
    • 读取接下来的 4 个字节以获取消息长度
    • 读取 x(在上一步获得)字节以获取消息

现在的问题是,有时当我在服务器部分发送消息的长度(例如:23045)时,我收到一个巨大的整数(例如:123106847)。

一个重要的线索是,这种情况在消息超过多个字符(在我的情况下 > 10K)时发生,如果我发送了一条较小的消息(例如 4-5k),一切都会按预期工作。

客户端发送部分(outputStream/inputStream均为BufferedXXXStream类型):

    private String getResponseFromServer( NormalizerActionEnum action, String message) throws IOException{

        writeByte( action.id());
        writeString( message);
        flush(;

        return read();
    }

    private String read() throws IOException{
        byte[] msgLen = new byte[4];
        inputStream.read(msgLen);
        int len = ByteBuffer.wrap(msgLen).getInt();
        byte[] bytes = new byte[len];
        inputStream.read(bytes);

        return new String(bytes);
    }

    private void writeByte( byte msg) throws IOException{
        outputStream.write(msg);
    }

    private void writeString( String msg) throws IOException{

        byte[] msgLen = ByteBuffer.allocate(4).putInt(msg.length()).array();

        outputStream.write(msgLen);
        outputStream.write(msg.getBytes());
    }

    private void flush() throws IOException{
        outputStream.flush();
    }

服务器部分(_input/_output 为 BufferedXXXStream 类型)

private byte readByte() throws IOException, InterruptedException {
    int b =  _input.read();
    while(b==-1){
        Thread.sleep(1);
        b = _input.read();
    }

    return (byte) b;
}

private String readString() throws IOException, InterruptedException {
    byte[] msgLen = new byte[4];
    int s = _input.read(msgLen);
    while(s==-1){
        Thread.sleep(1);
        s = _input.read(msgLen);
    }   

    int len = ByteBuffer.wrap(msgLen).getInt();     
    byte[] bytes = new byte[len];
    s = _input.read(bytes);
    while(s==-1){
        Thread.sleep(1);
        s = _input.read(bytes);
    }

    return new String(bytes);
}

private void writeString(String message) throws IOException {
    byte[] msgLen = ByteBuffer.allocate(4).putInt(message.length()).array();
    _output.write(msgLen);
    _output.write(message.getBytes());
    _output.flush();
}

....

byte cmd = readByte();
String message = readString();

任何帮助将不胜感激。如果您需要更多详细信息,请告诉我。

更新:由于 Jon SkeetEJP 的 cmets 我意识到服务器上的读取部分进行了一些毫无意义的操作,但抛开这一点,我终于明白了问题所在:关键是我在应用程序的整个长度内保持流打开,并且前几次我发送了消息长度我可以在服务器端读取它,但是 Jon Skeet 指出数据不会一次全部到达,所以当我尝试读取消息长度时再次,我实际上是从消息本身中读取信息,这就是为什么我有虚假的消息长度。

~而不是发送数据长度然后一次读取它,我发送它没有长度,我一次读取一个字节,直到完美工作的字符串结束

private String readString() throws IOException, InterruptedException {
    StringBuilder sb = new StringBuilder();
    byte[] bytes = new byte[100];
    int s = 0;
    int index=0;
    while(true){
        s = _input.read();
        if(s == 10){
            break;
        }
        bytes[index++] = (byte) (s);
        if(index == bytes.length){
            sb.append(new String(bytes));
            bytes = new byte[100];
            index=0;
        }           
    }
    if(index > 0){
        sb.append(new String(Arrays.copyOfRange(bytes, 0, index)));
    }

    return sb.toString();
}

【问题讨论】:

  • sleep() 毫无意义。 read() 已经阻塞,直到输入可用。而在返回值为 -1 的情况下睡觉和重新阅读就更没有意义了,因为肯定不会再有更多的东西要阅读了。你的意思是while (s != -1)
  • @EJP 你说得对,我知道现在这毫无意义,但撇开主要问题不谈,主要问题是我发送的长度而不是我收到的长度是一些随机情况

标签: java sockets tcp stream


【解决方案1】:

看看这个:

byte[] bytes = new byte[len];
s = _input.read(bytes);
while(s==-1){
    Thread.sleep(1);
    s = _input.read(bytes);
}

return new String(bytes);

首先,循环是没有意义的:read 唯一会返回 -1 的情况是它已关闭,在这种情况下循环不会对您有所帮助。

其次,您忽略了数据包含多个块的可能性。您假设如果您设法获得任何 数据,那么您就获得了所有 数据。相反,你应该像这样循环:

int bytesRead = 0;
while (bytesRead < bytes.length) {
    int chunk = _input.read(bytes, bytesRead, bytes.length - bytesRead);
    if (chunk == -1) {
        throw new IOException("Didn't get as much data as we should have");
    }
    bytesRead += chunk;
}

请注意,您的所有其他 InputStream.read 调用也假定您已设法读取数据,并且确实已读取所有您需要的数据。

哦,您正在使用平台默认编码在二进制数据和文本数据之间进行转换 - 这不是一个好主意。

你有什么理由不使用DataInputStreamDataOutputStream 来做这个吗?目前,您正在重新发明轮子,并在处理错误时这样做。

【讨论】:

  • +1 thx 输入,你说得对,因为我把所有数据都刷新了,所以我希望一次接收所有数据,我希望我可以应用你“块管理”,但问题出在@ 987654327@ : 相同情况下伪造的消息长度
  • 关于 DataInputStream 这是我的第一种方法,但与缓冲方法相比性能很慢
  • @Stephan:您可以将BufferedInputStream 包装在DataInputStream 中(同样适用于DataOutputStreamBufferedOutputStream)。不过不要忘记冲洗!
  • 是的,我想到了,但我担心由于额外的封装而导致性能下降,但我会尝试
  • 如果消息的长度被打乱,你知道我该如何管理块吗?
【解决方案2】:

您发送的代码有问题:

byte[] msgLen = ByteBuffer.allocate(4).putInt(message.length()).array();
_output.write(msgLen);
_output.write(message.getBytes());

您发送 字符数 作为消息长度,但之后将消息转换为字节。根据平台编码 String.getBytes() 可以给你比字符更多的字节。

您应该永远假设 String.length() 与 String.getBytes().length 有 任何 关系!这些是不同的概念,绝不能混为一谈。

【讨论】:

  • 我也想过,但事实并非如此,因为:1. 它在客户端和服务器上的平台相同 2. 在相同的情况下,它在其他情况下也可以工作
  • @Stephan 它不是不同的平台(尽管这也是一个潜在的头痛来源),它 String.length() 和 String.getBytes().length 可以根据 字符串内容(要清楚:"a".length() == "a".getBytes("UTF-8").length but "\u20AC".length != "\u20AC".getBytes("UTF-8").length)。您的代码存在错误,这就是为什么您会得到看似随机的结果。
  • 很公平......我用.getBytes().length而不是.length(),但问题是一样的
  • 你的阅读方法有一个类似的常见错误,Jon Skeet 已经指出:你不能确保你真的已经阅读了消息长度指定的字节数。 Jon Skeet 还展示了确保读取指定字节数的代码(第二个代码示例)。我以为你已经解决了这个问题,但也许它溜走了?
  • +1 为有效点,虽然我正在寻找答案,所以我终于明白了问题的关键是我在应用程序的整个长度和前几个保持打开流当我发送消息长度时,我能够在服务器端读取它,但是正如 Jon Skeet 指出的那样,数据不会一次全部到达,所以当我再次尝试读取消息长度时,我实际上是从消息中读取这就是为什么我有虚假的消息长度
猜你喜欢
  • 2020-12-05
  • 1970-01-01
  • 2014-02-01
  • 1970-01-01
  • 2013-06-09
  • 2012-07-17
  • 2020-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多