通过套接字(java)可靠地发送文件
我正在开发cient/server java应用程序。我写了两个类,一个用于发送文件,另一个用于接收文件。唯一的问题是,有时只发送半个字节(不知道为什么),客户端被阻塞,等待另一半到达。我正在我的机器上运行客户端和服务器进行测试。如何确保发送所有字节时不会丢失 文件发送者:通过套接字(java)可靠地发送文件,java,sockets,client-server,Java,Sockets,Client Server,我正在开发cient/server java应用程序。我写了两个类,一个用于发送文件,另一个用于接收文件。唯一的问题是,有时只发送半个字节(不知道为什么),客户端被阻塞,等待另一半到达。我正在我的机器上运行客户端和服务器进行测试。如何确保发送所有字节时不会丢失 文件发送者: OutputStream out = mSocket.getOutputStream(); FileInputStream fileIn = new FileInputStream(mFile
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.");
文件管理器接收器:
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.");
InputStream in=mSocket.getInputStream();
long startTime=System.currentTimeMillis();
/*读取字节*/
字节[]缓冲区=新字节[缓冲区大小];
int-read;
int totalRead=0;
FileOutputStream fileOut=新的FileOutputStream(mLocalFolder+“/”+mFileName);
while(totalRead 没有给出更多的细节,这几乎是不可能回答的。你可能想考虑使用NETY:它将处理所有你没有想到的问题,你也可以考虑使用BuffReDeUpTeStudio并记录异常。另外,尝试在单独的线程中运行它,这样当它失败时它不会阻塞,并且您可以重试/中止。