ejabberd connection using Smack in android giving

2019-07-25 16:36发布

Hello we have downloaded the ejabberd from this. domain is localhost and we have set the xmppDomain as my computer's ip address. I have used the following code for connection

    public static final String XMPP_DOMAIN = "localhost";
    public static final String XMPP_HOST = "10.0.2.2";//kept for emaulator
    //public static final String XMPP_HOST = "192.168.1.152"; //ip of my pc
    public static final int XMPP_PORT = 5222;
    public static final String XMPP_RESOURCE = "xmppdemo";
    public static final boolean XMPP_DEBUG = true;

      private void initialiseConnection() throws IOException, InterruptedException, XMPPException, SmackException {
        InetAddress addr = InetAddress.getByName(Constants.XMPP_HOST);
        DomainBareJid serviceName = JidCreate.domainBareFrom(Constants.XMPP_DOMAIN);

        XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration
                .builder();
        config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
        config.setXmppDomain(serviceName);
        config.setHostAddress(addr);
        config.setPort(Constants.XMPP_PORT);
        config.setDebuggerEnabled(Constants.XMPP_DEBUG);
        config.setResource(Constants.XMPP_RESOURCE);
        connection = new XMPPTCPConnection(config.build());
        connection.addConnectionListener(mConnectionListener);
        connection.addAsyncStanzaListener(mStanzaListener, new StanzaFilter() {
            @Override
            public boolean accept(Stanza stanza) {
                //You can also return only presence packets, since we are only filtering presences
                return true;
            }
        });

        Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.manual);
        roster = Roster.getInstanceFor(connection);
        roster.addRosterListener(mRoasterListener);


    }

     public void connect() {

        @SuppressLint("StaticFieldLeak") AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected synchronized Boolean doInBackground(Void... arg0) {
                //There is no point in reconnecting an already established connection. So abort, if we do
                if (connection.isConnected())
                    return false;

                //We are currently in "connection" phase, so no requests should be made while we are connecting.
                isconnecting = true;

                if (isToasted)
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(service, "connecting....", Toast.LENGTH_LONG).show();
                        }
                    });

                if (debug) Log.d(TAG, "connecting....");

                try {
                    connection.connect();

                    /**
                     * Set delivery receipt for every Message, so that we can confirm if message
                     * has been received on other end.
                     *
                     * @NOTE: This feature is not yet implemented in this example. Maybe, I'll add it later on.
                     * Feel free to pull request to add one.
                     *
                     * Read more about this: http://xmpp.org/extensions/xep-0184.html
                     **/

                    DeliveryReceiptManager dm = DeliveryReceiptManager.getInstanceFor(connection);
                    dm.setAutoReceiptMode(DeliveryReceiptManager.AutoReceiptMode.always);
                    dm.addReceiptReceivedListener(new ReceiptReceivedListener() {
                        @Override
                        public void onReceiptReceived(Jid fromJid, Jid toJid, String receiptId, Stanza receipt) {

                        }

//                        @Override
//                        public void onReceiptReceived(final String fromid,
//                                                      final String toid, final String msgid,
//                                                      final Stanza packet) {
//
//                        }
                    });
                    connected = true;

                } catch (IOException e) {
                    service.onConnectionClosed();
                    if (isToasted)
                        new Handler(Looper.getMainLooper())
                                .post(new Runnable() {

                                    @Override
                                    public void run() {
                                        Toast.makeText(service, "IOException: ", Toast.LENGTH_SHORT).show();
                                    }
                                });
                    if (debug) Log.e(TAG, "IOException: " + e.getMessage());
                } catch (SmackException e) {
                    service.onConnectionClosed();
                    if (isToasted)
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(service, "SMACKException: ", Toast.LENGTH_SHORT).show();
                            }
                        });
                    if (debug) Log.e(TAG, "SMACKException: " + e.getMessage());
                } catch (XMPPException e) {
                    service.onConnectionClosed();
                    if (isToasted)
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(service, "XMPPException: ", Toast.LENGTH_SHORT).show();
                            }
                        });
                    if (debug) Log.e(TAG, "XMPPException: " + e.getMessage());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //Our "connection" phase is now complete. We can tell others to make requests from now on.
                return isconnecting = false;
            }
        };
        connectionThread.execute();
    }
     //Signup to server
    public void Signup(SignupModel signupModel) {
        XMPPError.Condition condition = null;
        boolean errors = false;
        String errorMessage = "";

        String mUsername = signupModel.getUsername();
        String mPassword = signupModel.getPassword();

        boolean isPasswordValid = signupModel.checkPassword();
        boolean areFieldsValid = signupModel.validateFields();

        if (!isPasswordValid) {
            errors = true;
            errorMessage = Constants.SIGNUP_ERR_INVALIDPASS;
        }

        if (!areFieldsValid) {
            errors = true;
            errorMessage = Constants.SIGNUP_ERR_FIELDERR;
        }

        if (errors) {
            service.onSignupFailed(errorMessage);
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!connected && !isconnecting) connect();
            }
        }).start();

        try {
//            final AccountManager accountManager = AccountManager.getInstance(connection);
//
//
//            accountManager.createAccount(Localpart.from(mUsername), mPassword);


            AccountManager accountManager = AccountManager.getInstance(connection);
            accountManager.sensitiveOperationOverInsecureConnection(true);
            accountManager.createAccount(Localpart.from(mUsername), mPassword);

        } catch (XMPPException | SmackException e) {

            e.printStackTrace();
            if (debug) Log.e(TAG, "Username: " + mUsername + ",Password: " + mPassword);

            if (e instanceof XMPPException.XMPPErrorException) {
                condition = ((XMPPException.XMPPErrorException) e).getXMPPError().getCondition();
            }

            if (condition == null) {
                condition = XMPPError.Condition.internal_server_error;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (XmppStringprepException e) {
            e.printStackTrace();
        }

        if (condition == null) {
            service.onSignupSuccess();
        } else {
            switch (condition) {
                case conflict:
                    errorMessage = Constants.SIGNUP_ERR_CONFLICT;
                    break;
                case internal_server_error:
                    errorMessage = Constants.SIGNUP_ERR_SERVER_ERR;
                    break;
                default:
                    errorMessage = condition.toString();
                    break;

            }

            service.onSignupFailed(errorMessage);
        }
    }

    //Login to server
    public void login() {
        try {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (!connected && !isconnecting) connect();
                }
            }).start();

            if (debug) Log.i(TAG, "User " + userId + userPassword);

            connection.login(userId, userPassword);

            if (debug) Log.i(TAG, "Yey! We're logged in to the Xmpp server!");

            service.onLoggedIn();
        } catch (XMPPException | SmackException | IOException e) {

            service.onLoginFailed();
            if (debug) e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

When I run this code I an receiving the following exception (when tried to run from emulator)

SMACKException: The following addresses failed: '10.0.2.2:5222' failed because: /10.0.2.2 exception: java.net.SocketTimeoutException: failed to connect to /10.0.2.2 (port 5222) from /192.168.232.2 (port 34922) after 30000ms

when tried to run from my device I kept HOST_NAME as my pc's ip address, but then I am receiving the following error

E/XMPPHandler: SMACKException: The following addresses failed: '192.168.1.152:5222' failed because: /192.168.1.152 exception: java.net.SocketTimeoutException: connect timed out

When I installed ejabberd on my pc then I received the following Access Control List page Access Control List .. Should I have to change something?? Or missing something?

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-07-25 17:05

I had this problem too. I don't know why, but ejabberd server on windows does not works properly. I tried installing server on linux and mac, and it's working correctly. But on windows version always gets SocketTimeoutException.

查看更多
登录 后发表回答