分享一下Xmpp在iPhone和Android上断线后重连的注意点

这里所说的断线,不是WIFI或者3G网络的断线

OpenFire服务器本身有一个控制客户端与服务器连接时间的东西

如果超过这个时间,客户端与服务器之间的连接会被切断

这个时候需要重新连接

iOS上在做重连的时候,比较简单,能自动重连,唯一需要注意的是,重连成功后要重新发送一次认证请求
[self.xmppStream authenticateWithPassword:pwd error:&error];

Android上就有点头疼了,调了好久,其实代码很少,就是时机错了,另外,就是少了关键的一步,其实也是要再发一次认证请求

connectionClosed()这个方法会监测到断线,用户手动切断连接这里也会相应,自己需要判断一下
当监测到不是自己主动切断连接的时候,要自己手动重新连接。
但是,非常重要的一点!
要延迟一会,我自己是延迟了1000毫秒,就是因为一开始没有延迟,导致刚连上,又被切断连接了。

    public void connectionClosed() {

        if ( ChatApplication.getInstance().getIMConnect().isLogon() ) {

            reconnectHandler.postDelayed( reconnectRunnable, 1000 );
        }
    }

        reconnectRunnable = new Runnable() {

            @Override
            public void run() {

                Thread reconnectThread = new Thread() {

                    public void run() {

                        try {

                            isXmppReconnect = true;

                            IMConnect imConnect = ChatApplication.getInstance().getIMConnect();

                            imConnect.getIMConn().connect();
                        } 
                        catch ( Exception e ) {

                            isXmppReconnect = false;

                            runOnUiThread( new Runnable() {

                                @Override
                                public void run() {

                                    ToastUtil.showMsg("连接失败!");
                                    ChatApplication.getInstance().clearAllActivity();
                                    startActivity(new Intent(ActivityHome.this, ActivityLogin.class));
                                }
                            });
                        }
                    }
                };
                reconnectThread.start();
            }
        };

连接成功以后,还不行,要发送认证请求:

@Override
public void reconnectionSuccessful() {

        Log.e( "", " XmppStream Auto Reconnection Successful! " );

        if ( isXmppReconnect ) {

            isXmppReconnect = false;

            try {
                
                        IMConnect imConnect = ChatApplication.getInstance().getIMConnect();

                        imConnect.getIMConn().login( imConnect.getUserName(), imConnect.getPassWord() );
            } 
            catch ( Exception e ) {

                runOnUiThread( new Runnable() {

                            @Override
                            public void run() {

                                        ToastUtil.showMsg("连接失败!");
                                        ChatApplication.getInstance().clearAllActivity();
                                        startActivity(new Intent(ActivityHome.this, ActivityLogin.class));
                                }
                        } );
                }
        }
}

以上!

你可能感兴趣的:(Android,即时通讯)