Как отправить файл с Android-клиента на сервер C ++ через сокет

Я пытался отправить растровое изображение с моего Android на ПК (сервер сокетов 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 — длина

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

2

Решение

Задача ещё не решена.

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector