0

コンピューターの Windows フォーム アプリケーションに .txt ファイルを送信する Android アプリを作成しようとしています。問題は、ファイル全体が送信されないことです (問題が送信側にあるのか受信側にあるのかはわかりませんでした)。.txt ファイルの途中からランダムな部分だけを受信側に取得します。私は何を間違っていますか?奇妙なことは、それが数回完全に機能したことですが、今ではファイルの先頭または末尾を取得できません。

Android アプリは Java で作成され、Windows フォーム アプリは C# で作成されます。filepath は私のファイルの名前です。ここで何が問題なのですか?

Android アプリのコード (送信ファイル)

//create new byte array with the same length as the file that is to be sent

byte[] array = new byte[(int) filepath.length()];

FileInputStream fileInputStream = new FileInputStream(filepath);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
//use bufferedInputStream to read to end of file
bufferedInputStream.read(array, 0, array.length);
//create objects for InputStream and OutputStream
//and send the data in array to the server via socket
OutputStream outputStream = socket.getOutputStream();
outputStream.write(array, 0, array.length);

Windows フォーム アプリのコード (受信ファイル)

TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();

byte[] message = new byte[65535];
int bytesRead;

clientStream.Read(message, 0, message.Length);
System.IO.FileStream fs = System.IO.File.Create(path + dt);
//message has been received
ASCIIEncoding encoder = new ASCIIEncoding();
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));  
fs.Write(message, 0, bytesRead);
fs.Close();
4

1 に答える 1

0

完全な配列をメモリに読み込んで後で出力ストリームに送信する代わりに、読み書きを同時に行い、「小さな」バッファ バイト配列を使用するだけで済みます。このようなもの:

public boolean copyStream(InputStream inputStream, OutputStream outputStream){
    BufferedInputStream bis = new BufferedInputStream(inputStream);
    BufferedOutputStream bos = new BufferedOutputStream(outputStream);

    byte[] buffer = new byte[4*1024]; //Whatever buffersize you want to use.

    try {
        int read;
        while ((read = bis.read(buffer)) != -1){
            bos.write(buffer, 0, read);
        }
        bos.flush();
        bis.close();
        bos.close();
    } catch (IOException e) {
        //Log, retry, cancel, whatever
        return false;
    } 
    return true;
}

受信側でも同じことを行う必要があります。受信したバイトの一部を書き込み、使用する前に完全にメモリに保存しないでください。

これで問題が解決しない可能性がありますが、とにかく改善する必要があります。

于 2013-05-15T07:10:26.023 に答える