4
我想通過套接字從Android向服務器發送大文件,但服務器收到的文件不完整。在AndroidAndroid客戶端使用Socket發送大文件,服務器收到的文件不完整
代碼:
Socket client = new Socket(ipStr, 4444);
OutputStream outputStream = client.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
byte[] buffer = new byte[512];
byte[] sendLen = getBytes(file.length(), true);
outputStream.write(sendLen);
outputStream.flush();
int count;
while ((count = fileInputStream.read(buffer)) > 0)
{
outputStream.write(buffer, 0, count);
}
outputStream.flush();
bufferedInputStream.close();
outputStream.close();
client.close();
代碼在服務器上:
byte[] recvHead = new byte[8];
inStream.read(recvHead, 0, 8);
long recvLength = getLong(recvHead, false);
FileOutputStream file = new FileOutputStream(fileName, false);
byte[] buffer = new byte[8192];
int count = 0;
while (count < recvLength) {
int n = inStream.read(buffer);
if(n == -1)
break;
file.write(buffer, 0, n);
count += n;
}
但服務器將讀取(緩衝)阻塞(該文件的Android sended約30M)。
這裏是奇怪的事情: 當我發送文件時添加輸出到文件,服務器可以正常工作。
FileOutputStream file2 = new FileOutputStream("/sdcard/testfile" , false);
while ((count = fileInputStream.read(buffer)) >= 0)
{
outputStream.write(buffer, 0, count);
outputStream.flush();
file2.write(buffer, 0, count);
file2.flush();
}
任何人都可以幫助我嗎?謝謝!
實際上我使用這段代碼來確保服務器接收到8個字節的長度。 'int len = inStream.read(recvHead,0,8); \t \t \t \t int pos = len; \t \t \t \t而(LEN> = 0 && POS <8){ \t \t \t \t LEN = inStream.read(recvHead,POS,8 - POS); \t \t \t \t pos + = len; \t \t \t \t} \t' – user1656092
問題是服務器可以接收正確的文件長度,但文件內容不完整。謝謝! – user1656092
@ user1656092所以它還沒有被全部發送,正如你所說的,接收器在read()中仍然被阻塞。 – EJP