在Android中使用Smack进行ejabberd连接,给出连接超时错误 [英] ejabberd connection using Smack in android giving connection timed out error

查看:75
本文介绍了在Android中使用Smack进行ejabberd连接,给出连接超时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我们已经从 ..我是否必须更改某些内容?还是缺少什​​么?

解决方案

我遇到了类似的问题.我在Windows 10中安装了openfire serevr.我的代码是

  DomainBareJid xmppServiceDomain = JidCreate.domainBareFrom("desktop-urvfr83");//DomainBareJid xmppServiceDomain = JidCreate.domainBareFrom("192.168.1.3");InetAddress addr = InetAddress.getByName("192.168.1.3");XMPPTCPConnectionConfiguration配置= XMPPTCPConnectionConfiguration.builder().setUsernameAndPassword("alir","111111").setHostAddress(addr).setResource("phonn").setXmppDomain(xmppServiceDomain).setSecurityMode(ConnectionConfiguration.SecurityMode.disabled).setPort(5222).建造(); 

,但无法连接.当我禁用防火墙时,它可以正常工作并连接.

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 .. Should I have to change something?? Or missing something?

解决方案

I had similar problem. I have openfire serevr installed in windows 10. My code was

DomainBareJid xmppServiceDomain = JidCreate.domainBareFrom("desktop-urvfr83");
            //DomainBareJid xmppServiceDomain = JidCreate.domainBareFrom("192.168.1.3");
            InetAddress addr = InetAddress.getByName("192.168.1.3");

            XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
                    .setUsernameAndPassword("alir", "111111")
                    .setHostAddress(addr)
                    .setResource("phonn")
                    .setXmppDomain(xmppServiceDomain)
                    .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
                    .setPort(5222)
                    .build();

but it could not connect. When I disabled the firewall it worked correctly and connected.

这篇关于在Android中使用Smack进行ejabberd连接,给出连接超时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆