2011-08-03 58 views
2

我正在编程一个服务器客户端应用程序,并且在将来自服务器的二进制字节数组转换为设备时遇到问题。套接字通信问题[Android]

我用的代码是下一个:当歌曲已经下载

int bytesRead = 0; 
     FileOutputStream fos = new FileOutputStream(file); 
     DataOutputStream dosToFile = new DataOutputStream(fos); 
     long totalBytesWritten = 0; 
     byte[] buffer = new byte[5024]; 
     do { 
      bytesRead = dis.read(buffer, 0, 5024); 
      if (bytesRead > 0) { 
       dosToFile.write(buffer, 0, bytesRead); 
       dosToFile.flush(); 
       totalBytesWritten += bytesRead;    
       Log.e("", "Total Bytes written = "+ totalBytesWritten); 
      } else if (bytesRead == 0) { 
       Log.e("","Zero bytes readed when downloading song."); 
      } else if (bytesRead == -1) { 
       Log.e("","Read returned -1 when downloading song."); 
      } 
     } while (bytesRead > -1); 

的问题就来了。在最后一次读取中,在读完歌曲的最后几个字节(并将它们写入SD卡)之后,应用程序在读取中冻结,并且不会返回假设的-1。

代码显示错误?我应该以其他方式转移吗?

我把我的二进制数据,此代码:

byte [] mybytearray = new byte [(int)myFile.length()]; 
     mybytearray = this.fileToByteArray(myFile); 
     if (mybytearray != null) { 
      dos.write(mybytearray, 0, mybytearray.length); 
      dos.flush(); 
      System.out.println("Song send."); 
     } else { 
      System.out.println("The song could not be send."); 
     } 

非常感谢你。

回答

0

解决方案:

 int bytesRead = 0; 
     FileOutputStream fos = new FileOutputStream(file); 
     DataOutputStream dosToFile = new DataOutputStream(fos); 
     long totalBytesWritten = 0; 
     byte[] buffer = new byte[5024];  // 8Kb 
     do { 
      bytesRead = dis.read(buffer, 0, 5024); 
      if (bytesRead > 0) { 
       dosToFile.write(buffer, 0, bytesRead); 
       dosToFile.flush(); 
       totalBytesWritten += bytesRead;    //Se acumula el numero de bytes escritos en el fichero 
      } else if (bytesRead == 0) { 
       Log.e("","Zero bytes readed when downloading song."); 
      } else if (bytesRead == -1) { 
       Log.e("","Read returned -1 when downloading song."); 
      } 
      if (totalBytesWritten == fileLength) break; 
     } while (bytesRead > -1); 
0

试试这个:

int read = nis.read(buffer, 0, 4096); // This is blocking 

while (read != -1) { 
byte[] tempdata = new byte[read]; 
System.arraycopy(buffer, 0, tempdata, 0, read); 

// Log.i(NTAG, "Got data: " + new String(tempdata)); 
handler.sendMessage(handler.obtainMessage(MSG_NETWORK_GOT_DATA, tempdata)); 
read = nis.read(buffer, 0, 4096); // This is blocking 
} 

的处理仅仅是我将消息发送到解析(或写入文件)的方式。你可以在这里做任何事情。当完成读完刚完成的阅读时,不需要在循环内检查。你可以捕捉到诸如SocketTimeoutException等Excecptions来确定问题的原因。

+0

你好,杰克。它仍然在最后一次读取时被阻塞。我编辑了我的第一篇文章,向您展示如何从服务器发送数据。谢谢 – newlog

+0

最后,我解决了这个问题,将写入的字节与文件的总长度进行比较,如果它们相等则打破循环。 – newlog