简体   繁体   English

将数据从服务器发送到Android应用

[英]Send data from server to an Android app

How can I send data using sockets from a server to an Android app to display it? 如何使用套接字将数据从服务器发送到Android应用程序以显示数据?

My Android app takes a photo and sends it to a server located on a PC to stored it and detect how many faces has the picture and marked it using OpenCV. 我的Android应用程序拍摄了一张照片,并将其发送到PC上的服务器进行存储,并检测出有多少张脸并使用OpenCV对其进行了标记。

I want to send the value of the faces detected of the server, and the image with the marked faces, to the Android app, displaying this using a Toast and a ImageView respectively. 我想将检测到的服务器面部的值以及带有标记面部的图像发送到Android应用程序,分别使用ToastImageView显示。

This is the code of the server.- 这是服务器的代码。

 /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    package fileserver;

    /**
     *
     * @author Andrea
     */
    import java.io.BufferedOutputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import org.opencv.core.Core;
    import org.opencv.core.Mat;
    import org.opencv.core.MatOfRect;
    import org.opencv.core.Point;
    import org.opencv.core.Rect;
    import org.opencv.core.Scalar;
    import org.opencv.highgui.Highgui;
    import org.opencv.objdetect.CascadeClassifier;

    public class FileServer {

        public static void run() {  //byte[] imagen
            System.out.println("\nRunning DetectFaceDemo");

            // Create a face detector from the cascade file in the resources
            // directory.

            /*
            La clase CascadeClasifier se emplea para la detección de objetos.
            Cargamos el archivo claficador .xml para deteccion frontal de rostros.
            */
            CascadeClassifier faceDetector = new CascadeClassifier("C:\\opencv\\sources\\data\\lbpcascades\\lbpcascade_frontalface.xml");
            //CascadeClassifier faceDetector = new CascadeClassifier("C:\\opencv\\sources\\data\\lbpcascades\\haarcascade_frontalface_alt.xml");
            //Mat image = Highgui.imread("C:\\opencv\\shekhar.JPG");
            //Mat image = Highgui.imread("FotoTest1.jpg");

            /*
            La clase Mat almacena valores numéricos de cada punto de la imagen.
            */
            Mat image = Highgui.imread("src/Test.jpg");

            /* 
            Iniciamos la deteccion de rostros en la imagen.
            La clase MatOfRect es una clase contenedora especial para la clase Rect.
            */
            MatOfRect faceDetections = new MatOfRect();
            faceDetector.detectMultiScale(image, faceDetections);

            System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));

            /*
            Dibujamos un rectangulo en cada cara
            */
            for (Rect rect : faceDetections.toArray()) {
                Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
            }

            /*
            Guardamos la nueva imagen con los rostros detectados
            */
            String filename = "faceDetection3.png";
            System.out.println(String.format("Writing %s", filename));
            Highgui.imwrite(filename, image);
        }

        public static void main(String[] args) throws IOException {
            int filesize = 6022386; // filesize temporary hardcoded

            //Indispensable para el funcionamiento de OpenCV
            System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

            long start = System.currentTimeMillis();
            int bytesRead;
            int current = 0;

            // create socket
            ServerSocket servsock = new ServerSocket(5000);
            while (true) {
                System.out.println("Waiting...");

                Socket sock = servsock.accept();
                System.out.println("Accepted connection : " + sock);

                // receive file
                byte[] mybytearray = new byte[filesize];
                InputStream is = sock.getInputStream();
                FileOutputStream fos = new FileOutputStream("src/Test.jpg"); // destination

                BufferedOutputStream bos = new BufferedOutputStream(fos);
                bytesRead = is.read(mybytearray, 0, mybytearray.length);
                current = bytesRead;

                // thanks to A. Cádiz for the bug fix
                do {
                    bytesRead = is.read(mybytearray, current,
                            (mybytearray.length - current));
                    if (bytesRead >= 0) {
                        current += bytesRead;
                    }
                } while (bytesRead > -1);

                bos.write(mybytearray, 0, current);
                bos.flush();
                long end = System.currentTimeMillis();
                System.out.println(end - start);
                bos.close();

                /*
                Ejecutamos el algoritmo de deteccion de rostros
                */
                run();

                sock.close();
                System.out.println(fos.toString());
            }
        }
    }

And the Android app.- 还有Android应用-

package com.Cardiel.DTO;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.text.SimpleDateFormat;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.provider.MediaStore;

public class DTO extends Activity implements OnClickListener {
    private static final String PATTERN = "^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
    String ruta_fotos = Environment
            .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            + "/misfotos/";
    String path_file;
    File file = new File(ruta_fotos);
    Button btnCam, btnPrueba, btnEnviar;
    ImageView imagen;
    Intent i;
    Bitmap bmp;
    int cons;
    static final int SERVERPORT = 5000;
    String SERVER_IP;
    Socket cliente;
    DataInputStream input;
    BufferedInputStream bis;
    BufferedOutputStream bos;
    int in;
    byte[] byteArray;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dto);

        btnCam = (Button) findViewById(R.id.btnn1);
        /*btnPrueba = (Button) findViewById(R.id.btn2);*/
        btnEnviar = (Button) findViewById(R.id.btn3);
        imagen = (ImageView) findViewById(R.id.imageView1);

        /* image size */
        int width = 300, height = 200;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width,
                height);
        imagen.setLayoutParams(params);

        btnCam.setOnClickListener(this);
        /*btnPrueba.setOnClickListener(this);*/
        btnEnviar.setOnClickListener(this);
        file.mkdir();

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        switch (v.getId()) {

        case R.id.btnn1:
            path_file = ruta_fotos + getCode() + ".jpg";
            File mi_foto = new File(path_file);

            try {
                mi_foto.createNewFile();
            } catch (IOException ex) {
                Log.e("ERROR ", "Error:" + ex);
            }

            Uri uri = Uri.fromFile(mi_foto);

            i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            i.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(i, cons);
            break;

        /*case R.id.btn2:
            bmp = BitmapFactory.decodeResource(getResources(),
                    R.drawable.prueba);
            imagen.setImageBitmap(bmp);
            imagen.setEnabled(false);
            break;*/

        case R.id.btn3:
            if (imagen.isEnabled() == false) {
                hacerDialog();
            } else {
                Toast.makeText(this, "No se ha Seleccionado una imagen",
                        Toast.LENGTH_LONG).show();
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
        case Activity.RESULT_OK:

            bmp = readingImage(path_file);

            if (bmp != null) {
                imagen.setImageBitmap(bmp);
                imagen.setEnabled(false);
            }

            break;

        case Activity.RESULT_CANCELED:

            break;
        }
    }

    public String getCode() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
        String date = dateFormat.format(new Date());
        String photoCode = "pic_" + date;

        return photoCode;
    }

    private Bitmap readingImage(String _path) {
        Bitmap bitmap = null;
        File f = new File(_path);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;

        try {
            bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null,
                    options);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return bitmap;
    }

    public void hacerDialog() {
        AlertDialog.Builder alert = new AlertDialog.Builder(this);

        alert.setTitle("Ingrese IP");
        alert.setMessage("Direccion IP del Servidor");

        // Set an EditText view to get user input
        final EditText input = new EditText(this);
        alert.setView(input);

        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                boolean isIP = validate(input.getText().toString());
                if (isIP == true) {
                    SERVER_IP = input.getText().toString();
                    (new MySyncTask()).execute();
                } else {
                    Toast.makeText(DTO.this, "IP no es Valida",
                            Toast.LENGTH_LONG).show();
                }

            }
        });

        alert.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // Canceled.
                    }
                });

        alert.show();
    }

    public static boolean validate(final String ip) {

        Pattern pattern = Pattern.compile(PATTERN);
        Matcher matcher = pattern.matcher(ip);
        return matcher.matches();
    }

    class MySyncTask extends AsyncTask<Integer, Integer, String> {

        @Override
        protected String doInBackground(Integer... params) {

            try {
                cliente = new Socket(SERVER_IP, SERVERPORT);

                // Enviar archivo
                File myFile = new File(path_file);
                byte[] mybytearray = new byte[(int) myFile.length()];
                FileInputStream fis = new FileInputStream(myFile);
                BufferedInputStream bis = new BufferedInputStream(fis);
                bis.read(mybytearray, 0, mybytearray.length);
                OutputStream os = cliente.getOutputStream();
                // System.out.println("Sending...");
                os.write(mybytearray, 0, mybytearray.length);
                os.flush();

                fis.close();

                cliente.close();

            } catch (UnknownHostException e) {
                Log.v("ERROR", e.toString());
            } catch (IOException e) {
                Log.v("ERROR", e.toString());
            }

            return null;
        }
    }
}

And this is the .xml layout and the .manifest 这是.xml布局.manifest

I'll appreciate any help. 我将不胜感激。 Thanks. 谢谢。

write the results to the same socket from the server, and read them from the Android socket... 将结果从服务器写入相同的套接字,然后从Android套接字读取结果...

output.write(yourimage); // write prepareServer message to the server // here I use an object.. you, use your method.
    in = new ObjectInputStream(connection.getInputStream()); // get inputstream to read from the server!
    newMessageArrived = new incomming((int) transferr.length()); // Define new message object
    if ((newMessageArrived = (incomming) in.readUnshared()) != null) { // try to read result from server
    //... do ur stuff..
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM