我已经为服务器客户端通信创建了一个套接字编程 我使用的读取数据read(byte[])的DataInputStream,还用写数据write(byte[])的DataOutputStream.
当我发送少量数据时,我的程序运行正常.但是,如果我发送20000个字符的数据并发送10次,那么我能够完美地接收数据8次但不能接收2次.
那么我可以使用套接字编程中的读写来可靠地发送和接收数据吗?
我的猜测是你发出一个电话read()并假设它会返回你要求的所有数据.流通常不会那样工作.它将阻塞直到某些数据可用,但它不会等到它有足够的数据来填充数组.
通常这意味着循环.例如:
byte[] data = new byte[expectedSize];
int totalRead = 0;
while (totalRead < expectedSize)
{
int read = stream.read(data, totalRead, expectedSize-totalRead);
if (read == -1)
{
throw new IOException("Not enough data in stream");
}
totalRead += read;
}
Run Code Online (Sandbox Code Playgroud)
如果你不知道你首先想要多少字节,你可能仍然想要循环,但这次直到read()返回-1.使用缓冲区(例如8K)读入并写入ByteArrayOutputStream.读完后,可以将数据ByteArrayOutputStream作为字节数组从中获取.