Criei um aplicativo em java no android que envia os bytes de um arquivo .jpg por meio de um soquete e um soquete de servidor assíncrono em C # no Windows que recebe os bytes e os grava em um arquivo .jpg. O arquivo recebido não pode ser aberto.
No aplicativo java, que é o cliente, usei a seguinte classe asynctask executada no onCreate:
class asyncTask extends AsyncTask<Void,Void,Void>{
@Override
protected Void doInBackground(Void... voids) {
try {
final File myFile = new File("//sdcard/DCIM/Camera/img1.jpg");
byte[] bytes = new byte[(int) myFile.length()];
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(myFile));
buf.read(bytes, 0, bytes.length);
s = new Socket(ip,3333);
OutputStream OS = s.getOutputStream();
OS.write(bytes, 0, bytes.length);
OS.flush();
s.close();
} catch (IOException e) {
Log.d("Error",e.toString());
e.printStackTrace();
}
return null;
}
}
E no aplicativo C # eu recebi os dados e os salvei em um arquivo no seguinte método de retorno de chamada assíncrono que é chamado quando os dados são recebidos:
public static void ReadCallback(IAsyncResult ar)
{
Socket clientSocket = (Socket)ar.AsyncState;
int buffLength = clientSocket.EndReceive(ar);
Array.Resize(ref buffer, buffLength);
totaLength += buffLength;
buffer.CopyTo(allData, totaLength - 1);
if (buffLength == 0)
{
Array.Resize(ref allData, totaLength);
File.WriteAllBytes("C: /Users/fxavi/Desktop/img.jpg", allData);
Console.WriteLine(totaLength);
}
else
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), clientSocket);
}
Eu me sinto muito idiota depois de encontrar a solução para esse problema. Que é o que totaLength += buffLength;
deve ser executado antes buffer.CopyTo(allData, totaLength);
para que o buffer seja copiado para o índice correto.
Este artigo é coletado da Internet.
Se houver alguma infração, entre em [email protected] Delete.
deixe-me dizer algumas palavras