我正在开发一个客户端/服务器java应用程序。我写了两个类,一个用于发送文件,另一个用于接收文件。唯一的问题是有时只发送半个字节(不知道为什么),客户端被阻塞等待另一半到达。我在我的机器上运行客户端和服务器进行测试。如何确保所有字节都不会丢失?
文件发件人:
OutputStream out = mSocket.getOutputStream();
FileInputStream fileIn = new FileInputStream(mFile);
long startTime = System.currentTimeMillis();
/* Send bytes. */
byte[] buffer = new byte[BUFFER_SIZE];
int read;
int readTotal = 0;
while ((read = fileIn.read(buffer)) != -1) {
out.write(buffer, 0, read);
readTotal += read;
}
out.flush();
long endTime = System.currentTimeMillis();
System.out.println("\t" + readTotal + " bytes written in " + (endTime - startTime) + " ms.");
Filer接收器:
InputStream in = mSocket.getInputStream();
long startTime = System.currentTimeMillis();
/* Read bytes. */
byte[] buffer = new byte[BUFFER_SIZE];
int read;
int totalRead = 0;
FileOutputStream fileOut = new FileOutputStream(mLocalFolder + "/" + mFileName);
while (totalRead < mSize) {
read = in.read(buffer);
fileOut.write(buffer);
totalRead += read;
System.out.println("SO FAR " + totalRead + " OUT OF " + mSize);
}
fileOut.close();
long endTime = System.currentTimeMillis();
System.out.println("\tComplete. " + totalRead + " bytes read in " + (endTime - startTime) + "ms.");