套接字通信问题[Android]

时间:2011-08-03 19:05:34

标签: android sockets download communication

我正在编写服务器 - 客户端应用程序,当从服务器向设备传输一首歌作为二进制字节数组时,我遇到了问题。

我使用的代码是下一个:

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 );

问题出现在已下载歌曲时。在上一次读取中,在读完歌曲的最后几个字节(并将它们写入sdcard)后,应用程序在读取时冻结,并且不会返回假定的-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.");
        }

非常感谢。

2 个答案:

答案 0 :(得分: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等异常,以确定问题所在。

答案 1 :(得分: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 );