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

Java 将数据从服务器发送到Android应用程序,java,android,sockets,opencv,Java,Android,Sockets,Opencv,如何使用套接字将数据从服务器发送到Android应用程序以显示数据 我的Android应用程序会拍摄一张照片,并将其发送到位于PC上的服务器,以存储照片,并检测有多少张脸有照片,并使用OpenCV进行标记 我想将服务器检测到的人脸值以及带有标记人脸的图像发送到Android应用程序,分别使用Toast和ImageView显示 这是服务器的代码- /* * To change this license header, choose License Headers in Project

如何使用套接字将数据从服务器发送到Android应用程序以显示数据

我的Android应用程序会拍摄一张照片,并将其发送到位于PC上的服务器,以存储照片,并检测有多少张脸有照片,并使用OpenCV进行标记

我想将服务器检测到的人脸值以及带有标记人脸的图像发送到Android应用程序,分别使用
Toast
ImageView
显示

这是服务器的代码-

 /*
     * 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());
            }
        }
    }
还有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;
        }
    }
}
package com.Cardiel.DTO;
导入java.io.BufferedInputStream;
导入java.io.BufferedOutputStream;
导入java.io.DataInputStream;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileNotFoundException;
导入java.io.IOException;
导入java.io.ObjectInputStream;
导入java.io.ObjectOutputStream;
导入java.io.OutputStream;
导入java.net.Socket;
导入java.net.UnknownHostException;
导入java.util.Date;
导入java.util.regex.Matcher;
导入java.util.regex.Pattern;
导入java.text.simpleDataFormat;
导入android.app.Activity;
导入android.app.AlertDialog;
导入android.content.DialogInterface;
导入android.content.Intent;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.net.Uri;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.os.Environment;
导入android.util.Log;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.ImageView;
导入android.widget.LinearLayout;
导入android.widget.Toast;
导入android.provider.MediaStore;
公共类DTO扩展活动实现OnClickListener{
私有静态最终字符串模式=“^([01]?\\d\\d?| 2[0-4]\\d | 25[0-5])\\){3}([01]?\\d\\d?| 2[0-4]\\d | 25[0-5])$”;
字符串ruta_fotos=环境
.getExternalStoragePublicDirectory(Environment.DIRECTORY\u图片)
+“/misphotos/”;
字符串路径文件;
文件文件=新文件(ruta_fotos);
按钮btnCam、btnPrueba、btnEnviar;
ImageView imagen;
意图一;
位图bmp;
int cons;
静态最终int服务器端口=5000;
字符串服务器;
插座客户;
数据输入流输入;
缓冲数据流bis;
缓冲输出流;
int-in;
字节[]字节数组;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u dto);
btnCam=(按钮)findViewById(R.id.btnn1);
/*btnPrueba=(按钮)findViewById(R.id.btn2)*/
btnEnviar=(按钮)findViewById(R.id.btn3);
imagen=(ImageView)findViewById(R.id.imageView1);
/*图像大小*/
内部宽度=300,高度=200;
LinearLayout.LayoutParams参数=新的LinearLayout.LayoutParams(宽度,
高度);
imagen.setLayoutParams(参数);
btnCam.setOnClickListener(此);
/*btnPrueba.setOnClickListener(这个)*/
btnEnviar.setOnClickListener(此);
mkdir()文件;
}
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
开关(v.getId()){
案例R.id.btnn1:
path_file=ruta_fotos+getCode()+“.jpg”;
File mi_foto=新文件(路径文件);
试一试{
mi_foto.createNewFile();
}捕获(IOEX异常){
Log.e(“错误”,“错误:+ex”);
}
Uri=Uri.fromFile(mi_foto);
i=新意图(android.provider.MediaStore.ACTION\u IMAGE\u CAPTURE);
i、 putExtra(MediaStore.EXTRA_输出,uri);
startActivityForResult(一,cons);
打破
/*案例R.id.btn2:
bmp=BitmapFactory.decodeResource(getResources(),
R.可拉拔的prueba);
设置图像位图(bmp);
imagen.setEnabled(false);
中断*/
案例R.id.btn3:
if(imagen.isEnabled()==false){
hacerDialog();
}否则{
Toast.makeText(这是“No se ha Seleccionado una imagen”,
Toast.LENGTH_LONG).show();
}
}
}
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
开关(结果代码){
案例活动。结果\u正常:
bmp=读取图像(路径文件);
如果(bmp!=null){
设置图像位图(bmp);
imagen.setEnabled(false);
}
打破
案例活动.RESULT\u已取消:
打破
}
}
公共字符串getCode(){
SimpleDataFormat dateFormat=新的SimpleDataFormat(“yyyymmddhhmmss”);
字符串date=dateFormat.format(newdate());
字符串photoCode=“pic_”+日期;
返回光电码;
}
私有位图读取图像(字符串\u路径){
位图=空;
文件f=新文件(_路径);
BitmapFactory.Options=new-BitmapFactory.Options();
options.inPreferredConfig=Bitmap.Config.ARGB_8888;
试一试{
位图=BitmapFactory.decodeStream(新文件输入流(f),null,
选择权);
}catch(filenotfounde异常){
e、 printStackTrace();
}
返回位图;
}
公共空间hacerDialog(){
AlertDialog.Builder alert=新建AlertDialog.Builder(此);
警报。设置标题(“入口IP”);
警报.setMessage(“Direccion IP del Servidor”);
//设置EditText视图以获取用户输入
最终编辑文本输入=新编辑文本(本);
alert.setView(输入);
alert.setPositiveButton(“确定”,新的DialogInterface.OnClickListener(){
public void onClick(对话框接口对话框,int whichButton){
布尔isIP=validate(input.getText().toString())
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..
    }