簡體   English   中英

套接字通信問題[Android]

[英]Problem with socket communication [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 );

當歌曲已經下載后,問題就來了。 在最后一次讀取中,讀取歌曲的最后一個字節(並將它們寫入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.");
        }

非常感謝你。

嘗試這個:

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等,以確定可能是什么問題。

解:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM