[英]Sending very large string trough socket from server to android client
I have a problem with sending large string through socket from server to android client. 我通过服务器端从套接字向Android客户端发送大字符串时遇到问题。
String is about 10MB. 字符串约为10MB。
int socketTimeout = 200;
socket = new Socket(client.getHost(), client.getPort());
socket.setSoTimeout(socketTimeout);
OutputStreamWriter oos=new OutputStreamWriter(socket.getOutputStream());
String d = data.getData().toString() + "\n";
oos.write(d);
oos.flush();
Socket s = params[0];
InputStream is = null;
try {
is = s.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[32768];
while ((nRead = is.read(data, 0, data.length)) != -1) {
baos.write(data, 0, nRead);
}
return new String(baos.toByteArray());
}
So problem comes at line where I'm reading from inputStream
where I get OutOfMemoryException. 所以问题出在我从
inputStream
中读取OutOfMemoryException的地方。 I tried using different examples of reading string from stream. 我尝试使用从流读取字符串的不同示例。 I tried with
BufferedInputStream
, InputStreamReader
, IOUtils
, StringBuilder
, BufferedReader
..etc. 我尝试了
BufferedInputStream
, InputStreamReader
, IOUtils
, StringBuilder
, BufferedReader
IOUtils
。 and all of them give me OutOfMemory exception when the string is large. 当字符串很大时,它们都给我OutOfMemory异常。 I tested with smaller data something around 100K and it works perfectly.
我用较小的数据测试了大约10万,它可以很好地工作。
Exception that I get on server-side is "Connection is reset by peer, socket write error." 我在服务器端遇到的异常是“连接被对等方重置,套接字写入错误”。
You can read byte by byte in the client and write to a File byte by byte, in that way you are not holding the whole string in memory. 您可以在客户端中逐字节读取并逐字节写入File,这样就不会在内存中保留整个字符串。
And then of course read that file by tokens or lines, not the whole string at once 然后当然要通过标记或行读取该文件,而不是一次读取整个字符串
By storing it in a ByteArrayOutputStream
(or similar), you are coming up against the maximum heap size for the JVM in Android. 通过将其存储在
ByteArrayOutputStream
(或类似文件)中,您将遇到Android中JVM的最大堆大小。 This is a different size depending on the device. 这取决于设备的大小。 See: Android heap size on different phones/devices and OS versions
请参阅: 不同手机/设备和操作系统版本上的Android堆大小
As has already been suggested, you should consider using a file stream to write the received data to disk. 正如已经建议的那样,您应该考虑使用文件流将接收到的数据写入磁盘。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.