android - unity android wifi socket通信通过Android DLL

标签 android sockets unity-game-engine dll chat

我们能够在两个原生安卓应用和两个基于 Unity 的安卓应用之间建立 socket wifi 聊天。现在根据新的要求,我们需要开发两个统一的应用程序,其中包含带有客户端和服务器代码的 android dll。

我们需要通过这些 DLL 连接两个基于 unity 的 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 中。我可以调用这些类和方法,但无法建立连接。

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");

任何类型的帮助都是值得赞赏的。谢谢

最佳答案

好吧,我已经解决了这个问题。问题是在许可中。我没有在 Unity 的默认 list 文件中添加权限。

关于android - unity android wifi socket通信通过Android DLL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52074066/

相关文章:

android - 保存 Canvas 以供将来使用

c# - System.Net.GlobalLog - 如何查看其输出?

Java TCP 服务器无法接收来自多个客户端的消息

unity-game-engine - Unity 多显示器不工作

android - 如何根据随机数显示不同的说法

java - 如何围绕正方形移动图像

c++ - Linux 中 C++ 的 UDP Socket 编程

variables - 从其他脚本访问变量

android - 启用 64 位后,Unity 游戏在 Android 设备上滞后

java - Android 初学者 - 在不同 Activity 中使用变量或文件的方法?