繁体   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