簡體   English   中英

通過android DLL的Unity android wifi套接字通信

[英]Unity android wifi socket communication through Android DLL

我們能夠在兩個本機android應用程序和兩個基於Unity的android應用程序之間建立套接字wifi聊天。 現在,根據新要求,我們需要開發兩個統一的應用程序,其中包含帶有客戶端代碼和服務器代碼的android dll。

我們需要通過這些DLL連接兩個基於統一的android應用,然后,我們需要開始它們之間的通信。

Android服務器DLL

public class Server {
    Activity activity;
    ServerSocket serverSocket;
    String message = "";
    static final int socketServerPORT = 8082;

    private static volatile Server sSoleInstance;

    //private constructor.
    private Server(Activity activity) {

        //Prevent form the reflection api.
        if (sSoleInstance != null) {
            throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
        } else {
            this.activity = activity;
            Thread socketServerThread = new Thread(new SocketServerThread());
            socketServerThread.start();
        }
    }

    public static Server getInstance(Activity activity) {
        if (sSoleInstance == null) { //if there is no instance available... create new one
            synchronized (Client.class) {
                if (sSoleInstance == null) sSoleInstance = new Server(activity);
            }
        }

        return sSoleInstance;
    }

/*  public Server(Activity activity) {
        this.activity = activity;
        Thread socketServerThread = new Thread(new SocketServerThread());
        socketServerThread.start();
    }*/

    public int getPort() {
        return socketServerPORT;
    }

    public void onDestroy() {
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private class SocketServerThread extends Thread {

        int count = 0;

        @Override
        public void run() {
            try {
                serverSocket = new ServerSocket(socketServerPORT);

                while (true) {
                    Socket socket = serverSocket.accept();
                    count++;
                    message += "#" + count + " from "
                            + socket.getInetAddress() + ":"
                            + socket.getPort() + "\n";

                    activity.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //activity.msg.setText(message);
                            Log.e("server message", message);
                        }
                    });

                    SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
                            socket, count);
                    socketServerReplyThread.run();

                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    private class SocketServerReplyThread extends Thread {

        private Socket hostThreadSocket;
        int cnt;

        SocketServerReplyThread(Socket socket, int c) {
            hostThreadSocket = socket;
            cnt = c;
        }

        @Override
        public void run() {
            OutputStream outputStream;
            String msgReply = "Hello from Server, you are #" + cnt;

            try {
                outputStream = hostThreadSocket.getOutputStream();
                PrintStream printStream = new PrintStream(outputStream);
                printStream.print(msgReply);
                printStream.close();

                message += "replayed: " + msgReply + "\n";

                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                    //  activity.msg.setText(message);
                        Log.e("server message", message);
                    }
                });

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                message += "Something wrong! " + e.toString() + "\n";
            }

            activity.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Log.e("server message", message);
                    //activity.msg.setText(message);
                }
            });
        }

    }

    public String getIpAddress() {
        String ip = "";
        try {
            Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
                    .getNetworkInterfaces();
            while (enumNetworkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = enumNetworkInterfaces
                        .nextElement();
                Enumeration<InetAddress> enumInetAddress = networkInterface
                        .getInetAddresses();
                while (enumInetAddress.hasMoreElements()) {
                    InetAddress inetAddress = enumInetAddress
                            .nextElement();

                    if (inetAddress.isSiteLocalAddress()) {
                        ip += "Server running at : "
                                + inetAddress.getHostAddress();
                    }
                }
            }

        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            ip += "Something Wrong! " + e.toString() + "\n";
        }
        return ip;
    }
}

Android客戶端DLL代碼。

public class Client extends AsyncTask<Void, Void, Void> {

    String dstAddress;
    int dstPort = 8082;
    String response = "";
    String textResponse;

    private static volatile Client sSoleInstance;

    //private constructor.
    private Client(String addr, String textRespons) {

        //Prevent form the reflection api.
        if (sSoleInstance != null) {
            throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
        } else {
           dstAddress = addr;
           this.textResponse = textRespons;
           execute();
        }
    }

    public static Client getInstance(String addr, String textRespons) {
        if (sSoleInstance == null) { //if there is no instance available... create new one
            synchronized (Client.class) {
                if (sSoleInstance == null) sSoleInstance = new Client(addr, textRespons);
            }
        }

        return sSoleInstance;
    }

    //Make singleton from serialize and deserialize operation.
   /* protected Client readResolve() {
        return getInstance();
    }*/

    /*Client(String addr,  String textResponse) {
        dstAddress = addr;
        //dstPort = port;
        this.textResponse = textResponse;
    }
*/
    @Override
    protected Void doInBackground(Void... arg0) {

        Socket socket = null;

        try {
            socket = new Socket(dstAddress, dstPort);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
                    1024);
            byte[] buffer = new byte[1024];

            int bytesRead;
            InputStream inputStream = socket.getInputStream();

            /*
             * notice: inputStream.read() will block if no data return
             */
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
                response += byteArrayOutputStream.toString("UTF-8");
            }

        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = "UnknownHostException: " + e.toString();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = "IOException: " + e.toString();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        Log.e("Client response",response);
        //textResponse.setText(response);
        super.onPostExecute(result);
    }

}

我已經通過這些代碼創建了android DLL,並添加到Unity中。 我可以調用這些類和方法,但不能建立Connection。

Unity客戶端代碼

 string ipAddress = inputFieldMacAddress.text.ToString();
        string response = "message";

        AndroidJavaClass myAndroidClass = new AndroidJavaClass("com.braintech.commoncommunicationport.socket_client.ClientMainClass");
        AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
        AndroidJavaObject myAndroidPlugin = myAndroidClass.CallStatic<AndroidJavaObject>("getInstance", ipAddress, response);

        myAndroidPlugin.Call("startClient", ipAddress, response); 

Unity服務器代碼

   AndroidJavaClass myAndroidClass = new AndroidJavaClass("com.braintech.commoncommunicationport.socket_server.Server");
        AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
        AndroidJavaObject myAndroidPlugin = myAndroidClass.CallStatic<AndroidJavaObject>("getInstance", activity);
      int port=  myAndroidPlugin.Call<int>("getPort");

任何類型的幫助都是有意義的。 謝謝

好吧,我已經解決了這個問題。 允許發布問題。 我尚未在Unitys默認清單文件中添加權限。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM