Android LANでのリモート制御(呼び出し方法、データ取得)

20396 ワード

開発環境:Android Studioライブラリファイルダウンロード:implementation'com.google.code.gson:gson:2.6.2’の重要な知識:Socketの熟練したインタフェースコールバック全体の考え方はsocket通信に基づいて操作タイプとデータを1つのエンティティクラスにカプセル化することである.jsonによるパスピット:1 socket通信ポート番号1024(1024以内はシステムポート番号)2 gson依存を追加してAndroid MainfestファイルにINTERNETネットワークアクセス権を追加する
まず、データ転送の基本形式であるSocketModuleを見てみましょう.
package base;
/**
 * Created by zhongwang on 2018/1/22.
 */

public class SocketModule {
    /**
     *                        
     */
    private String operateType;
    /**
     *       (                      json     )
     */
    private String baseModule;

    public String getOperateType() {
        return operateType;
    }

    public void setOperateType(String operateType) {
        this.operateType = operateType;
    }

    public String getBaseModule() {
        return baseModule;
    }

    public void setBaseModule(String baseModule) {
        this.baseModule = baseModule;
    }
}

次に、サービス側ツールクラスです.WifiConnectUtilは、WifiConnectUtilを初期化した後、startObserverメソッドを呼び出してビジネスクラスインタフェースに転送します.
package cn.ml_tech.mx.mlservice.Util;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.ml_tech.mx.mlservice.base.MlServerApplication;
import cn.ml_tech.mx.mlservice.base.SocketModule;

/**
 *     : 2017/12/26
 *    : Administrator
 *     :
 */

public class WifiConnectUtil {
    private static WifiConnectUtil wifiConnectUtil;
    private MlServerApplication mlServerApplication;
    private String ipAddress = "";
    private ExecutorService threadPool;//   
    private ServerSocket serverSocket;
    private ToastUtil toastUtil;
    private Context context;
    private PrintWriter printWriter;
    private InputStream inputStream;
    private Gson gson;
    private Operate operate;

    public WifiConnectUtil(Context context) {
        this.context = context;
        mlServerApplication = (MlServerApplication) context.getApplicationContext();
        gson = mlServerApplication.getGson();
        toastUtil = ToastUtil.getInstance(context);
        ipAddress = "192.168.3.135";
        threadPool = Executors.newCachedThreadPool();
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    serverSocket = new ServerSocket(8888);
                    while (true) {
                        LogUtil.out(LogUtil.Debug, "    ");
                        Socket server = serverSocket.accept();
                        printWriter = new PrintWriter(server.getOutputStream(), true);//           
                        LogUtil.out(LogUtil.Debug, "    ");
                        printWriter.println(MlConCommonUtil.CONNECTSUCESS);
                        inputStream = server.getInputStream();

                    }

                } catch (IOException e) {
                    e.printStackTrace();
                    LogUtil.out(LogUtil.Debug, "io  ");
                }
            }
        });

    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public static WifiConnectUtil getWifiConnectUtil(Context context) {
        if (wifiConnectUtil == null)
            wifiConnectUtil = new WifiConnectUtil(context);
        return wifiConnectUtil;
    }

    /**
     *             
     *
     * @param operate
     */
    public void startObserver(Operate operate) {
        //       while  +     
        this.operate = operate;
        LogUtil.out(LogUtil.Debug, "startObserver");
        new Thread() {
            @Override
            public void run() {
                super.run();
                 while (true) {
                    try {
                        if (inputStream != null) {
                            if (inputStream.available() != 0) {
                                //           
                                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                                String res = bufferedReader.readLine();
                                LogUtil.out(LogUtil.Debug, res);
                                SocketModule socketModule = gson.fromJson(res, SocketModule.class);//  json
                                handlerOperate(socketModule);//    
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        LogUtil.out(LogUtil.Debug, "startObserver IOException");
                    }
                }
            }
        }.start();
    }


    /**
     *       
     *
     * @param socketModule
     */
    private void handlerOperate(SocketModule socketModule) {
        String operateType = socketModule.getOperateType();//      
        Object operateResult = null;
        switch (operateType) {//switch             
            case MlConCommonUtil.LOGIN:
                operateResult = operate.login(socketModule);//            
                socketModule.setBaseModule(gson.toJson(operateResult));//     
        }
        String res = gson.toJson(socketModule);//     json   
        LogUtil.out(LogUtil.Debug,"      ,        ");
        printWriter.println(res);
        LogUtil.out(LogUtil.Debug,"      ");

    }

    /**
     *     
     */
    public interface Operate {
        Object login(SocketModule socketModule);
    }
}

もう一つはクライアントです
package util;

import android.os.Handler;
import android.util.Log;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import base.MlApplication;
import base.SocketModule;

/**
 * Created by zhongwang on 2018/1/19.
 */

public class MlConnectUtil {
    /**
     *        888    get set    
     */
    private  int port = 8888;
    /**
     *             
     */
    private  BufferedReader bufferedReader;
    /**
     *             
     */
    private  PrintWriter printWriter;
    private  InputStream inputStream;
    private  ExecutorService threadPool;
    private  MlApplication mlApplication;
    private static  MlConnectUtil mlConnectUtil;
    private Handler handler;
    private Gson gson;
    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public MlConnectUtil(MlApplication application) {
        mlApplication = application;
        gson = mlApplication.getGson();
        handler = new Handler();
        Log.d("ZWW",mlApplication.isConnected()+" sssss");
    }

    public static MlConnectUtil getMlConnectUtil(MlApplication application){
        if(mlConnectUtil==null)
            mlConnectUtil = new MlConnectUtil(application);
                    return mlConnectUtil;
    }
    private  Socket clientSocket;

    public  BufferedReader getBufferedReader() {
        return bufferedReader;
    }

    public  void setBufferedReader(BufferedReader bufferedReader) {
        this.bufferedReader = bufferedReader;
    }

    public  PrintWriter getPrintWriter() {
        return printWriter;
    }

    public  void setPrintWriter(PrintWriter printWriter) {
        this.printWriter = printWriter;
    }
    public  void getDataFromMotor(final SocketModule socketModule, final OperateData operateData){
        Log.d("zww","      ,        ");
        new Thread(){
            @Override
            public void run() {
                super.run();
              printWriter.println(mlApplication.getGson().toJson(socketModule));
                startObserver(operateData);
            }
        }.start();
    }

    private void startObserver(final OperateData operateData) {
        try {
        while(true){
            if(inputStream!=null&inputStream.available()!=0){
              String moduleRes=  bufferedReader.readLine();
              Log.d("zww","                "+moduleRes);
              final SocketModule socketModule = gson.fromJson(moduleRes,SocketModule.class);
              handler.post(new Runnable() {
                  @Override
                  public void run() {
                      operateData.handlerData(socketModule);
                  }
              });
            }
        }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     *   socket      
     *
     * @param ipAddress ip  
     */
    public  void ConnectServer(final String ipAddress, final MlApplication mlApplication) {
        threadPool = Executors.newCachedThreadPool();
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    if (clientSocket != null) {
                        clientSocket.close();
                    }
                    clientSocket = new Socket(ipAddress, port);
                    Log.d("zww","      ");
                    inputStream  = clientSocket.getInputStream();
                    bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                    String res = bufferedReader.readLine();
                    mlApplication.setConnected(res.equals(MlConCommonUtil.CONNECTSUCESS));
                    if(mlApplication.isConnected()){
                        printWriter = new PrintWriter(clientSocket.getOutputStream(),true);
                    }
                    Log.d("zww",res);
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.d("zww", "clientSocket Create faulure");
                    if(printWriter!=null)
                        printWriter.close();
                    if(bufferedReader!=null)
                        try {
                            bufferedReader.close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                }
            }
        });
    }

    /**
     *         
     */
    public interface OperateData{
       void handlerData(SocketModule socketModule);
    }
}

必要なものがあればgithubアドレスを見てください.https://github.com/zw21544182/MlMobile