简体   繁体   English

服务器套接字读取长字符串

[英]Server socket read long string

I have a question about reading bytes from server socket.我有一个关于从服务器套接字读取字节的问题。 I'm using the default values ​​for literacy 8192b bytes on the network.我正在使用网络上读写 8192b 字节的默认值。 The problem is that there are times you need to send files larger than the buffer capacity.问题是有时您需要发送大于缓冲区容量的文件。 To avoid increasing the buffer as you can know that those packets arriving at different times are related?为了避免增加缓冲区,您可以知道那些在不同时间到达的数据包是相关的吗?

Client side snippet:客户端片段:

{
String c = xxxxx //imagine that it an string format JSON with 64000bites length
OutputStream wsOS = socket.getOutputStream();
wsOS.write(new String(data,"UTF-8"));
wsOS.flush();
}

When server side received the JSON string:当服务器端收到 JSON 字符串时:

{

 byte[] buffer = new byte[8192];
 int size = 0;

 StringBuilder str = new StringBuilder();

 size = wsIS.read(buffer);

if (size > 0) {

    str.append(new String(buffer, "UTF-8")
            .substring(0, size));

    while (wsIS.available() > 0) {
        size = wsIS.read(buffer);
        str.append(new String(buffer, "UTF-8")
                .substring(0, size));
    }

}
}

Problem:问题:

All string arrived in the server but in block 8192b - I can not concatenate the string because I don't know if the last string JSON is part of the previews.所有字符串都到达服务器,但在块 8192b 中 - 我无法连接字符串,因为我不知道最后一个字符串 JSON 是否是预览的一部分。

Even if you increase the buffer size there is no guarantee that the whole string will be read in a single call to wsIS.read .即使您增加缓冲区大小,也不能保证在对wsIS.read的单个调用中读取整个字符串。

What this means is that you must have some mechanism to know where the previous string has ends and new one begins.这意味着您必须有某种机制来知道前一个字符串的结束位置和新字符串的开始位置。 Some choices are as follows:一些选择如下:

  1. Use ObjectOutputStream / ObjectInputStream使用ObjectOutputStream / ObjectInputStream
  2. Write number of characters before actually writing the characters.在实际写入字符之前先写入字符数。 On the reading side, read the length and then those many chars在阅读方面,阅读长度,然后阅读那些许多字符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM