通过Android DLL的Unity android wifi套接字通信

时间:2018-08-29 09:29:28

标签: android sockets unity3d dll chat

我们能够在两个本机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中。我可以调用这些类和方法,但无法建立连接。

统一客户端代码

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

任何类型的帮助都是有意义的。谢谢

1 个答案:

答案 0 :(得分:0)

好,我已经解决了这个问题。允许发布问题。我尚未在Unitys默认清单文件中添加权限。