如何通过socket将文件从Android客户端发送到C ++服务器

时间:2012-11-22 10:08:59

标签: android c++ sockets file-transfer

我试图从我的android发送位图到PC(C ++套接字服务器),但失败了。发送完毕后,PNG文件无法打开

1 - 这是代码我将位图压缩为png格式

ByteArrayOutputStream bos = new ByteArrayOutputStream();
tmpBM.compress(CompressFormat.PNG, 0, bos); // compress to png format
byte[] bitmapdata = bos.toByteArray(); // new byte[] to send via socket
sendFile(bitmapdata, bitmapdata.length); // call sendFile method

2 - 这里是sendFile方法代码。 arr是字节数组,len是arr.length

public void sendFile(byte[] arr, int len) throws Exception{

    byte[] buf = new byte[1024];
    int cur = 0; // current byte reading
    sendMessage("Send\n"); // talk server

    sendMessage(String.valueOf(len)); // send file size
    // OutputStream outStream = ...;
    while (len-cur>0){
        if (len-cur>=1024){
            buf = copy(arr, cur, 1024); // copy to buf, from arr, offset cur, size 1024 byte
            outStream.write(buf, 0, 1024);
            cur+=1024;
        }// send 1024 byte if file size >1024
        else {
            buf = copy(arr, cur, len-cur);
            buf[len-cur] = '\0';
            outStream.write(buf, 0, len-cur);
        }// send remaining byte
    }
    outStream.flush();
}

3 - 这是代码接收文件

    char rec[50] = "";
    FILE *fw = fopen("tmp.png", "wb");
    printf("\n Created file");
    int recs = recv( current_client, rec, 32, 0 );
    rec[recs]='\0';
    int size = atoi(rec);
    printf("\n Have size %d", size);
    while(size > 0)
    {
        char buffer[1030]; // create buffer
        printf("\nLoop %d", size);
        if(size>=1024) // if remaining >1024 byte, read 1024 byte
        {
            recv( current_client, buffer, 1024, 0 );
            fwrite(buffer, 1024, 1, fw);
        }
        else // else read all
        {
            recv( current_client, buffer, size, 0 );
            buffer[size]='\0';
            fwrite(buffer, size, 1, fw);
        }
            size -= 1024;
    }
    fclose(fw);

0 个答案:

没有答案