Enviar / Recibir archivo / imagen Socket C # Android
Mi servidor envía la imagen al cliente:
Servidor en c #:
- InetAddress.getLocalHost (). GetHostAddress () devuelve 127.0.0.1 en Android
- Cliente-Servidor: Transferencia de archivos de Android a PC conectada vía socket
- ¿Cómo puede mi aplicación Android comunicarse con un daemon nativo?
- Crear SSLSocket por SSLSocketFactory con tiempo de espera de conexión establecido
- Tiempo de espera de conexión de socket Android
//Create, Bind Socket and listen Client IPAddress localAddress = IPAddress.Parse("10.0.0.3"); IPEndPoint ipEndpoint = new IPEndPoint(localAddress, 2200); listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listenSocket.Bind(ipEndpoint); listenSocket.Listen(10); Console.WriteLine("Server start: {0}", ipEndpoint); while (true) { clientSock = listenSocket.Accept(); } //Path file String img = "C:\\Users\\Kostya\\Documents\\img.jpg"; //Get Info from Image FileInfo FileInfo = new FileInfo(img); //Create byte array of size Image byte[] sizeBuf = new byte[8]; //Convert (long) file info to string String fInfoStr = FileInfo.Length.ToString(); //Add 0 pre string if lenght string < 8 while (fInfoStr.Length < 8) { fInfoStr = "0" + fInfoStr; } //Convert strring to byte array countBuf = Encoding.ASCII.GetBytes(fInfoStr); //Send byte array sckt.Send(countBuf, SocketFlags.None); //Create byte array of byte image byte[] fBuffer = new byte[FileInfo.Length]; //FileStream FileStream fs = new FileStream(img, FileMode.Open, FileAccess.Read); //Read byte from image fs.Read(fBuffer,0,fBuffer.Length); fs.Flush(); fs.Close(); Console.WriteLine("Buffer: " + fBuffer.Length); //Send byte array sckt.Send(fBuffer, SocketFlags.None); Console.WriteLine("Отправили!");
Cliente en Android: // Crear una nueva tarea new AsyncTask () {
@Override protected Void doInBackground(Void... voids) { try { //Create Socket and connect to server mSocket = new Socket("10.0.0.3", 2200); Log.e("TCP", "Client connect"); if (mSocket.isConnected()){ //get Input Stream from Socket InputStream iStream = mSocket.getInputStream(); //Create byte array of size image byte[] countBuf = new byte[8]; //read size iStream.read(countBuf); //Convert to String String readTxt = new String(countBuf); //Parse int from string int SizeFile = Integer.parseInt(readTxt); Log.e("TCP", "Read size file " + readTxt + " : " + SizeFile); //Create directory new File(Environment.getExternalStorageDirectory() + File.separator + "myDirectory").mkdirs(); Log.e("TCP", "Create Drkt"); //Create Image(File) new File(Environment.getExternalStorageDirectory() + File.separator + "myDirectory", "img.jpg").createNewFile(); Log.e("TCP", "Create Img"); try { //Start read byte of image FileOutputStream fOutputStream = new FileOutputStream(Environment.getExternalStorageDirectory() + File.separator + "myDirectory" + File.separator + "img.jpg"); BufferedOutputStream BufOutputStream = new BufferedOutputStream(fOutputStream); byte[] aByte = new byte[SizeFile]; int bytesRead; //Read from server while ((bytesRead = iStream.read(aByte)) != -1) { Log.e("TCP", "Save to file"); //Write to file BufOutputStream.write(aByte, 0, bytesRead); } BufOutputStream.flush(); BufOutputStream.close(); mSocket.close(); } catch (Exception ex) { ex.printStackTrace(); } } } catch (Exception ex) { Log.e("TCP", "C: Error", ex); } return null; } }.execute();
Cliente c # (por ejemplo):
IPAddress localAddress = IPAddress.Parse("10.0.0.3"); IPEndPoint ipEndpoint = new IPEndPoint(localAddress, 2200); Socket sckt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sckt.Connect(ipEndpoint); if (sckt.Connected){ byte[] countBuf = new byte[8]; sckt.Receive(countBuf); int countData = BitConverter.ToInt32(countBuf, 0); byte[] dataBufer = new byte[countData]; sckt.Receive(dataBufer); FileStream fs = File.Create("C:\\Users\\Kostya\\Documents\\imgGet.jpg"); fs.Write(dataBufer, 0, dataBufer.Length); fs.Close(); sckt.Close(); }
Este código está funcionando completamente. Puedes usarlo.
- Envío de datos TCP desde Android (como cliente) - ¿no se envían datos?
- Conexión de dos teléfonos Android para transferir datos entre ellos a través de WIFI
- ¿Cuál es el tiempo de espera predeterminado de java.net.Socket en android?
- Cliente Android / socket de servidor Java; Android enviar pero no recibir?
- ¿El zócalo del cliente androide, cómo leer datos?
- Android: ¿Cómo detectar la aplicación eliminada de la lista de aplicaciones recientes?
- Cómo enviar el archivo binario y el texto usando el mismo socket
- 'Permiso denegado' al conectarse al socket unix abstracto
- Gradle configuration.apt definición
- Inicio de sesión de Facebook con la aplicación no instalada redirecciona a la página de inicio de sesión