XMPP即时通讯协议使用(三)——订阅发布、断开重连与Ping

XMPP即时通讯协议使用(三)——订阅发布、断开重连与Ping
https://blog.csdn.net/ctwy291314/article/details/80608300

package com.testV3;

import java.util.List;

import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smackx.pubsub.ItemPublishEvent;
import org.jivesoftware.smackx.pubsub.LeafNode;
import org.jivesoftware.smackx.pubsub.PayloadItem;
import org.jivesoftware.smackx.pubsub.PubSubManager;
import org.jivesoftware.smackx.pubsub.SubscribeForm;
import org.jivesoftware.smackx.pubsub.Subscription;
import org.jivesoftware.smackx.pubsub.listener.ItemEventListener;
import org.jivesoftware.smackx.xdata.packet.DataForm;
import org.jxmpp.jid.parts.Resourcepart;

public class SubscribeThread extends Thread {

    private String[] nodeId;

    private String userName;

    private String password;

    private String xmppDomain;

    private String serverName;

    private XMPPTCPConnection connection;

    private ItemEventListener<PayloadItem> myInterface;

    /**
     * 
     * @param userName
     * @param password
     * @param xmppDomain
     * @param serverName
     * @param nodeId
     *            监听节点集合
     */
    public SubscribeThread(String userName, String password, String xmppDomain, String serverName, String[] nodeId) {
        this.userName = userName;
        this.password = password;
        this.xmppDomain = xmppDomain;
        this.serverName = serverName;
        this.nodeId = nodeId;
        try {
            if (connection == null) {
                getConnection(userName, password, xmppDomain, serverName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 
     * @param userName
     * @param password
     * @param xmppDomain
     * @param serverName
     * @param nodeId
     *            监听节点集合
     * @param myInterface
     *            监听数据处理接口
     */
    public SubscribeThread(String userName, String password, String xmppDomain, String serverName, String[] nodeId,
            ItemEventListener myInterface) {
        this.userName = userName;
        this.password = password;
        this.xmppDomain = xmppDomain;
        this.serverName = serverName;
        this.nodeId = nodeId;
        this.myInterface = myInterface;
        try {
            if (connection == null) {
                getConnection(userName, password, xmppDomain, serverName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     * 
     * @param userName
     * @param password
     * @param xmppDomain
     * @param serverName
     */
    public void getConnection(String userName, String password, String xmppDomain, String serverName) {
        try {
            XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
            configBuilder.setUsernameAndPassword(userName, password);
            configBuilder.setXmppDomain(xmppDomain);
            /*Resourcepart resource = Resourcepart.from("pc");
            configBuilder.setResource(resource);*/
            configBuilder.setSendPresence(true);
            //configBuilder.setSendPresence(false);// 状态设为离线,目的为了取离线消息 
            configBuilder.setDebuggerEnabled(true);//设置Debugger模式
            configBuilder.setSecurityMode(XMPPTCPConnectionConfiguration.SecurityMode.disabled);

            connection = new XMPPTCPConnection(configBuilder.build());
            connection.addConnectionListener(new MyConnectionListener(connection, nodeId, myInterface));
            // 连接服务器
            connection.connect();

            // 登录服务器
            connection.login();
            /*Presence presence = new Presence(Presence.Type.available);  
            connection.sendPacket(presence);  */
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void run() {
        while (true) {

        }
    }
}
package com.testV3;

import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.StanzaListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.StanzaFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.packet.StreamError;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smackx.ping.PingFailedListener;
import org.jivesoftware.smackx.pubsub.ConfigurationEvent;
import org.jivesoftware.smackx.pubsub.ItemPublishEvent;
import org.jivesoftware.smackx.pubsub.LeafNode;
import org.jivesoftware.smackx.pubsub.PayloadItem;
import org.jivesoftware.smackx.pubsub.PubSubManager;
import org.jivesoftware.smackx.pubsub.SubscribeForm;
import org.jivesoftware.smackx.pubsub.Subscription;
import org.jivesoftware.smackx.pubsub.listener.ItemEventListener;
import org.jivesoftware.smackx.pubsub.listener.NodeConfigListener;
import org.jivesoftware.smackx.xdata.packet.DataForm;
import org.jxmpp.jid.parts.Resourcepart;

public class MyConnectionListener implements ConnectionListener, PingFailedListener {

    private String[] nodeId;

    private XMPPTCPConnection connection;

    private ItemEventListener myInterface;

    private boolean subscribed = false; // 是否已注册监听订阅事件

    private Timer tPing;
    private Timer tReconn;
    private int logintime = 30 * 1000;

    class ReconnTimetask extends TimerTask {
        @Override
        public void run() {
            if (!connection.isConnected() || !connection.isAuthenticated()) {
                System.out.println("断开重连...");
                connection.disconnect();
                // 连接服务器
                try {
                    connection.connect();
                    // 登录服务器
                    connection.login();
                    Presence presence = new Presence(Presence.Type.available);
                    connection.sendPacket(presence);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    class PingTimetask extends TimerTask {
        @Override
        public void run() {
            if (connection.isConnected() && connection.isAuthenticated()) {
                Presence presence = new Presence(Presence.Type.available);
                try {
                    connection.sendPacket(presence);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    public MyConnectionListener(XMPPTCPConnection connection, String[] nodeId) {
        this.connection = connection;
        this.nodeId = nodeId;
    }

    public MyConnectionListener(XMPPTCPConnection connection, String[] nodeId, ItemEventListener myInterface) {
        this.connection = connection;
        this.nodeId = nodeId;
        this.myInterface = myInterface;
    }

    public void connected(XMPPConnection connection) {
        // TODO Auto-generated method stub
        System.out.println("connection");
    }

    public void authenticated(final XMPPConnection connection, boolean resumed) {
        // TODO Auto-generated method stub
        System.out.println("authenticated");

        try {
            if (!subscribed) {
                subscribed = true;

                // ping定时器3分钟
                //tPing = new Timer();
                //tPing.schedule(new PingTimetask(), logintime, 3 * 60 * 1000);

                // 添加订阅监听
                if (myInterface == null) {
                    subscribeListener(nodeId, new MyItemEventListener());
                } else {
                    subscribeListener(nodeId, myInterface);
                }

                MyPingManager.setDefaultPingInterval(30);// Ping every 10 seconds
                MyPingManager myPingManager = MyPingManager.getInstanceFor(connection);
                // Set PingListener here to catch connect status
                myPingManager.registerPingFailedListener(MyConnectionListener.this);

                // 添加接受数据监听
                connection.addAsyncStanzaListener(new StanzaListener() {
                    public void processStanza(Stanza packet) throws NotConnectedException, InterruptedException {
                        // TODO Auto-generated method stub
                        System.out.println("截获的内容:" + packet.toXML());
                        if (packet instanceof Presence) {
                            Presence presence = (Presence) packet;
                            System.out.println("在线状态:" + presence.getType());
                            if (presence.getType().equals(Presence.Type.unavailable)) {// 证明已掉线
                                tReconn = new Timer();
                                tReconn.schedule(new ReconnTimetask(), logintime);
                            }
                        }
                    }
                }, new StanzaFilter() {
                    public boolean accept(Stanza stanza) {
                        // TODO Auto-generated method stub
                        return true;
                    }
                });
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void connectionClosed() {
        // TODO Auto-generated method stub
        System.out.println("connectionClosed");

        try {
            tReconn = new Timer();
            tReconn.schedule(new ReconnTimetask(), logintime);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void connectionClosedOnError(Exception e) {
        // TODO Auto-generated method stub
        System.out.println("connectionClosedOnError");

        try {
            tReconn = new Timer();
            tReconn.schedule(new ReconnTimetask(), logintime);
        } catch (Exception ee) {
            e.printStackTrace();
            ee.printStackTrace();
        }
    }

    public void reconnectionSuccessful() {
        // TODO Auto-generated method stub
        System.out.println("reconnectionSuccessful");
    }

    public void reconnectingIn(int seconds) {
        // TODO Auto-generated method stub
        System.out.println("reconnectingIn");
    }

    public void reconnectionFailed(Exception e) {
        // TODO Auto-generated method stub
        System.out.println("reconnectionFailed");
    }

    /**
     * 订阅节点监听及数据处理
     * 
     * @param nodeId
     * @param myItemEventListener
     * @throws Exception
     */
    public void subscribeListener(String[] nodeId, ItemEventListener<PayloadItem> myItemEventListener)
            throws Exception {
        PubSubManager mgr = PubSubManager.getInstance(connection);
        if (nodeId != null && nodeId.length > 0) {
            for (String id : nodeId) {
                // Get the node
                LeafNode node = null;

                node = mgr.getNode(id);

                SubscribeForm subscriptionForm = new SubscribeForm(DataForm.Type.submit);
                subscriptionForm.setDeliverOn(true);
                subscriptionForm.setDigestFrequency(5000);
                subscriptionForm.setDigestOn(true);
                subscriptionForm.setIncludeBody(true);

                if (myItemEventListener != null) {
                    node.removeItemEventListener(myItemEventListener);
                    node.addItemEventListener(myItemEventListener);
                } else {

                    myItemEventListener = new ItemEventListener<PayloadItem>() {
                        public void handlePublishedItems(ItemPublishEvent<PayloadItem> items) {
                            List<PayloadItem> list = (List<PayloadItem>) items.getItems();
                            for (PayloadItem item : list) {
                                System.out.println("订阅消息内容:" + item.getPayload().toXML());
                            }
                        }
                    };

                    node.removeItemEventListener(myItemEventListener);
                    node.addItemEventListener(myItemEventListener);
                }

                List<Subscription> subscriptions = node.getSubscriptions();

                boolean flag = true;
                if (subscriptions != null && subscriptions.size() > 0) {
                    for (Subscription s : subscriptions) {
                        if (s.getJid().toLowerCase()
                                .equals(connection.getUser().asEntityBareJidString().toLowerCase())) {// 已订阅过
                            flag = false;
                            break;
                        }
                    }
                }
                if (flag) {// 未订阅,开始订阅
                    node.subscribe(connection.getUser().asEntityBareJidString(), subscriptionForm);
                }
            }
        }
    }

    public void pingFailed() {
        // TODO Auto-generated method stub
        if (connection.isConnected()) {
            connection.disconnect();
        }
        tReconn = new Timer();
        tReconn.schedule(new ReconnTimetask(), logintime);
    }
}
package com.testV3;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.jivesoftware.smackx.pubsub.ItemPublishEvent;
import org.jivesoftware.smackx.pubsub.PayloadItem;
import org.jivesoftware.smackx.pubsub.listener.ItemEventListener;

class MyItemEventListener implements ItemEventListener<PayloadItem> {
    public void handlePublishedItems(ItemPublishEvent<PayloadItem> items) {
        List<PayloadItem> list = (List<PayloadItem>) items.getItems();
        for (PayloadItem item : list) {
            Date d = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //System.out.println("当前时间:" + sdf.format(d));
            System.out.println(sdf.format(d)+",订阅消息内容:" + item.getPayload().toXML());
        }
    }
}
package com.testV3;

/**
*
* Copyright 2012-2015 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jivesoftware.smack.AbstractConnectionClosedListener;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.ConnectionCreationListener;
import org.jivesoftware.smack.Manager;
import org.jivesoftware.smack.XMPPConnectionRegistry;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.iqrequest.AbstractIqRequestHandler;
import org.jivesoftware.smack.iqrequest.IQRequestHandler.Mode;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.IQ.Type;
import org.jivesoftware.smack.util.SmackExecutorThreadFactory;
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
import org.jivesoftware.smackx.ping.PingFailedListener;
import org.jivesoftware.smackx.ping.packet.Ping;
import org.jxmpp.jid.DomainBareJid;
import org.jxmpp.jid.Jid;

/**
 * Implements the XMPP Ping as defined by XEP-0199. The XMPP Ping protocol
 * allows one entity to ping any other entity by simply sending a ping to the
 * appropriate JID. PingManger also periodically sends XMPP pings to the server
 * to avoid NAT timeouts and to test the connection status.
 * <p>
 * The default server ping interval is 30 minutes and can be modified with
 * {@link #setDefaultPingInterval(int)} and {@link #setPingInterval(int)}.
 * </p>
 * 
 * @author Florian Schmaus
 * @see <a href="http://www.xmpp.org/extensions/xep-0199.html">XEP-0199:XMPP
 *      Ping</a>
 */
public class MyPingManager extends Manager {
    private static final Logger LOGGER = Logger.getLogger(MyPingManager.class.getName());

    private static final Map<XMPPConnection, MyPingManager> INSTANCES = new WeakHashMap<XMPPConnection, MyPingManager>();

    static {
        XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
            public void connectionCreated(XMPPConnection connection) {
                getInstanceFor(connection);
            }
        });
    }

    /**
     * Retrieves a {@link MyPingManager} for the specified {@link XMPPConnection},
     * creating one if it doesn't already exist.
     * 
     * @param connection
     *            The connection the manager is attached to.
     * @return The new or existing manager.
     */
    public static MyPingManager getInstanceFor(XMPPConnection connection) {
        MyPingManager MyPingManager = INSTANCES.get(connection);
        if (MyPingManager == null) {
            MyPingManager = new MyPingManager(connection);
            INSTANCES.put(connection, MyPingManager);
        }
        return MyPingManager;
    }

    /**
     * The default ping interval in seconds used by new MyPingManager instances. The
     * default is 30 minutes.
     */
    private static int defaultPingInterval = 60 * 30;

    /**
     * Set the default ping interval which will be used for new connections.
     *
     * @param interval
     *            the interval in seconds
     */
    public static void setDefaultPingInterval(int interval) {
        defaultPingInterval = interval;
    }

    private final Set<PingFailedListener> pingFailedListeners = Collections
            .synchronizedSet(new HashSet<PingFailedListener>());

    private final ScheduledExecutorService executorService;

    /**
     * The interval in seconds between pings are send to the users server.
     */
    private int pingInterval = defaultPingInterval;

    private ScheduledFuture<?> nextAutomaticPing;

    private MyPingManager(XMPPConnection connection) {
        super(connection);
        executorService = Executors
                .newSingleThreadScheduledExecutor(new SmackExecutorThreadFactory(connection, "Ping"));
        ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection);
        sdm.addFeature(Ping.NAMESPACE);

        connection.registerIQRequestHandler(
                new AbstractIqRequestHandler(Ping.ELEMENT, Ping.NAMESPACE, Type.get, Mode.async) {
                    @Override
                    public IQ handleIQRequest(IQ iqRequest) {
                        Ping ping = (Ping) iqRequest;
                        return ping.getPong();
                    }
                });
        connection.addConnectionListener(new AbstractConnectionClosedListener() {
            @Override
            public void authenticated(XMPPConnection connection, boolean resumed) {
                maybeSchedulePingServerTask();
            }

            @Override
            public void connectionTerminated() {
                maybeStopPingServerTask();
            }
        });
        maybeSchedulePingServerTask();
    }

    /**
     * Pings the given jid. This method will return false if an error occurs. The
     * exception to this, is a server ping, which will always return true if the
     * server is reachable, event if there is an error on the ping itself (i.e. ping
     * not supported).
     * <p>
     * Use {@link #isPingSupported(String)} to determine if XMPP Ping is supported
     * by the entity.
     * 
     * @param jid
     *            The id of the entity the ping is being sent to
     * @param pingTimeout
     *            The time to wait for a reply in milliseconds
     * @return true if a reply was received from the entity, false otherwise.
     * @throws NoResponseException
     *             if there was no response from the jid.
     * @throws NotConnectedException
     */
    public boolean ping(DomainBareJid jid, long pingTimeout) throws NotConnectedException, NoResponseException {
        final XMPPConnection connection = connection();
        // Packet collector for IQs needs an connection that was at least authenticated
        // once,
        // otherwise the client JID will be null causing an NPE
        if (!connection.isAuthenticated()) {
            throw new NotConnectedException();
        }
        Ping ping = new Ping(jid);
        try {
            connection.createStanzaCollectorAndSend(ping).nextResultOrThrow(pingTimeout);
        } catch (XMPPException exc) {
            return jid.equals(connection.getServiceName());
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return true;
    }

    /**
     * Same as calling {@link #ping(String, long)} with the defaultpacket reply
     * timeout.
     * 
     * @param jid
     *            The id of the entity the ping is being sent to
     * @return true if a reply was received from the entity, false otherwise.
     * @throws NotConnectedException
     * @throws NoResponseException
     *             if there was no response from the jid.
     */
    public boolean ping(DomainBareJid jid) throws NotConnectedException, NoResponseException {
        return ping(jid, connection().getPacketReplyTimeout());
    }

    /**
     * Query the specified entity to see if it supports the Ping protocol (XEP-0199)
     * 
     * @param jid
     *            The id of the entity the query is being sent to
     * @return true if it supports ping, false otherwise.
     * @throws XMPPErrorException
     *             An XMPP related error occurred during the request
     * @throws NoResponseException
     *             if there was no response from the jid.
     * @throws NotConnectedException
     */
    public boolean isPingSupported(Jid jid) throws NoResponseException, XMPPErrorException, NotConnectedException,InterruptedException {
        return ServiceDiscoveryManager.getInstanceFor(connection()).supportsFeature(jid, Ping.NAMESPACE);
    }

    /**
     * Pings the server. This method will return true if the server is reachable. It
     * is the equivalent of calling <code>ping</code> with the XMPP domain.
     * <p>
     * Unlike the {@link #ping(String)} case, this method will return true even if
     * {@link #isPingSupported(String)} is false.
     * 
     * @return true if a reply was received from the server, false otherwise.
     * @throws NotConnectedException
     */
    public boolean pingMyServer() throws NotConnectedException {
        return pingMyServer(true);
    }

    /**
     * Pings the server. This method will return true if the server is reachable. It
     * is the equivalent of calling <code>ping</code> with the XMPP domain.
     * <p>
     * Unlike the {@link #ping(String)} case, this method will return true even if
     * {@link #isPingSupported(String)} is false.
     *
     * @param notifyListeners
     *            Notify the PingFailedListener in case of error if true
     * @return true if the user's server could be pinged.
     * @throws NotConnectedException
     */
    public boolean pingMyServer(boolean notifyListeners) throws NotConnectedException {
        return pingMyServer(notifyListeners, connection().getPacketReplyTimeout());
    }

    /**
     * Pings the server. This method will return true if the server is reachable. It
     * is the equivalent of calling <code>ping</code> with the XMPP domain.
     * <p>
     * Unlike the {@link #ping(String)} case, this method will return true even if
     * {@link #isPingSupported(String)} is false.
     *
     * @param notifyListeners
     *            Notify the PingFailedListener in case of error if true
     * @param pingTimeout
     *            The time to wait for a reply in milliseconds
     * @return true if the user's server could be pinged.
     * @throws NotConnectedException
     */
    public boolean pingMyServer(boolean notifyListeners, long pingTimeout) throws NotConnectedException {
        boolean res;
        try {
            res = ping(connection().getServiceName(), pingTimeout);
        } catch (NoResponseException e) {
            res = false;
        }
        if (!res && notifyListeners) {
            for (PingFailedListener l : pingFailedListeners)
                l.pingFailed();
        }
        return res;
    }

    /**
     * Set the interval in seconds between a automated server ping is send. A
     * negative value disables automatic server pings. All settings take effect
     * immediately. If there is an active scheduled server ping it will be canceled
     * and, if <code>pingInterval</code> is positive, a new one will be scheduled in
     * pingInterval seconds.
     * <p>
     * If the ping fails after 3 attempts waiting the connections reply timeout for
     * an answer, then the ping failed listeners will be invoked.
     * </p>
     *
     * @param pingInterval
     *            the interval in seconds between the automated server pings
     */
    public void setPingInterval(int pingInterval) {
        this.pingInterval = pingInterval;
        maybeSchedulePingServerTask();
    }

    /**
     * Get the current ping interval.
     *
     * @return the interval between pings in seconds
     */
    public int getPingInterval() {
        return pingInterval;
    }

    /**
     * Register a new PingFailedListener
     *
     * @param listener
     *            the listener to invoke
     */
    public void registerPingFailedListener(PingFailedListener listener) {
        pingFailedListeners.add(listener);
    }

    /**
     * Unregister a PingFailedListener
     *
     * @param listener
     *            the listener to remove
     */
    public void unregisterPingFailedListener(PingFailedListener listener) {
        pingFailedListeners.remove(listener);
    }

    private void maybeSchedulePingServerTask() {
        maybeSchedulePingServerTask(0);
    }

    /**
     * Cancels any existing periodic ping task if there is one and schedules a new
     * ping task if pingInterval is greater then zero.
     *
     * @param delta
     *            the delta to the last received stanza in seconds
     */
    private void maybeSchedulePingServerTask(int delta) {
        maybeStopPingServerTask();
        if (pingInterval > 0) {
            int nextPingIn = pingInterval - delta;
            LOGGER.fine("Scheduling ServerPingTask in " + nextPingIn + " seconds (pingInterval=" + pingInterval
                    + ", delta=" + delta + ")");
            nextAutomaticPing = executorService.schedule(pingServerRunnable, nextPingIn, TimeUnit.SECONDS);
        }
    }

    private void maybeStopPingServerTask() {
        if (nextAutomaticPing != null) {
            nextAutomaticPing.cancel(true);
            nextAutomaticPing = null;
        }
    }

    /**
     * Ping the server if deemed necessary because automatic server pings are
     * enabled ({@link #setPingInterval(int)}) and the ping interval has expired.
     */
    public void pingServerIfNecessary() {
        final int DELTA = 1000; // 1 seconds
        final int TRIES = 3; // 3 tries
        final XMPPConnection connection = connection();
        // final XMPPConnection connection = this.connection;
        if (connection == null) {
            // connection has been collected by GC
            // which means we can stop the thread by breaking the loop
            return;
        }
        if (pingInterval <= 0) {
            // Ping has been disabled
            return;
        }
        long lastStanzaReceived = connection.getLastStanzaReceived();
        if (lastStanzaReceived > 0) {
            long now = System.currentTimeMillis();
            // Delta since the last stanza was received
            int deltaInSeconds = (int) ((now - lastStanzaReceived) / 1000);
            // If the delta is small then the ping interval, then we can defer the ping
            if (deltaInSeconds < pingInterval) {
                maybeSchedulePingServerTask(deltaInSeconds);
                return;
            }
        }
        if (connection.isAuthenticated()) {
            boolean res = false;

            for (int i = 0; i < TRIES; i++) {
                if (i != 0) {
                    try {
                        Thread.sleep(DELTA);
                    } catch (InterruptedException e) {
                        // We received an interrupt
                        // This only happens if we should stop pinging
                        return;
                    }
                }
                try {
                    res = pingMyServer(false);
                    /* Log.i("XMPP Ping", "result:"+res); */
                } catch (SmackException e) {
                    LOGGER.log(Level.WARNING, "SmackError while pinging server", e);
                    res = false;
                }
                // stop when we receive a pong back
                if (res) {
                    break;
                }
            }
            if (!res) {
                for (PingFailedListener l : pingFailedListeners) {
                    l.pingFailed();
                }
            } else {
                // Ping was successful, wind-up the periodic task again
                maybeSchedulePingServerTask();
            }
        } else {
            LOGGER.warning("XMPPConnection was not authenticated");
        }
    }

    private final Runnable pingServerRunnable = new Runnable() {
        public void run() {
            LOGGER.fine("ServerPingTask run()");
            pingServerIfNecessary();
        }
    };

    @Override
    protected void finalize() throws Throwable {
        LOGGER.fine("finalizing MyPingManager: Shutting down executor service");
        try {
            executorService.shutdown();
        } catch (Throwable t) {
            LOGGER.log(Level.WARNING, "finalize() threw throwable", t);
        } finally {
            super.finalize();
        }
    }
}
package com.testV3;

public class Test3 {

    final static String USERNAME = "gm";

    final static String PASSWORD = "123456";

    final static String XMPPDOMAIN = "172.19.12.240";

    final static String SERVERNAME = "pc-20170308pkrs";

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] nodeId = {"/BAGGL/GJXX/LCGJ","/BAGGL/GJXX/TLGJ"};
        SubscribeThread smark = new SubscribeThread(USERNAME,PASSWORD,XMPPDOMAIN,SERVERNAME,nodeId,new MyItemEventListener());

        smark.start();

    }

}

XMPP中的订阅流程

1、首先,需要确认你的服务器支持pubsub特性

1.1 查询XMPP服务的所有服务

<?xml version="1.0" encoding="utf-8"?>

<iq to="pc-20170308pkrs" id="3EV56-7" type="get">
  <query xmlns="http://jabber.org/protocol/disco#info"></query>
</iq>

返回:

<?xml version="1.0" encoding="utf-8"?>

<iq type="result" id="3EV56-7" from="pc-20170308pkrs" to="gm@pc-20170308pkrs/pc">
  <query xmlns="http://jabber.org/protocol/disco#info">
    <identity category="server" name="Openfire Server" type="im"/>
    <identity category="pubsub" type="pep"/>
    <feature var="http://jabber.org/protocol/pubsub#retrieve-default"/>
    <feature var="http://jabber.org/protocol/pubsub#purge-nodes"/>
    <feature var="vcard-temp"/>
    <feature var="http://jabber.org/protocol/pubsub#subscribe"/>
    <feature var="http://jabber.org/protocol/pubsub#subscription-options"/>
    <feature var="http://jabber.org/protocol/pubsub#create-nodes"/>
    <feature var="http://jabber.org/protocol/pubsub#outcast-affiliation"/>
    <feature var="msgoffline"/>
    <feature var="http://jabber.org/protocol/pubsub#get-pending"/>
    <feature var="http://jabber.org/protocol/pubsub#multi-subscribe"/>
    <feature var="http://jabber.org/protocol/pubsub#presence-notifications"/>
    <feature var="urn:xmpp:ping"/>
    <feature var="jabber:iq:register"/>
    <feature var="http://jabber.org/protocol/pubsub#delete-nodes"/>
    <feature var="http://jabber.org/protocol/pubsub#config-node"/>
    <feature var="http://jabber.org/protocol/pubsub#retrieve-items"/>
    <feature var="http://jabber.org/protocol/pubsub#auto-create"/>
    <feature var="http://jabber.org/protocol/disco#items"/>
    <feature var="http://jabber.org/protocol/pubsub#item-ids"/>
    <feature var="http://jabber.org/protocol/pubsub#meta-data"/>
    <feature var="jabber:iq:roster"/>
    <feature var="http://jabber.org/protocol/pubsub#instant-nodes"/>
    <feature var="http://jabber.org/protocol/pubsub#modify-affiliations"/>
    <feature var="http://jabber.org/protocol/pubsub#persistent-items"/>
    <feature var="http://jabber.org/protocol/pubsub#create-and-configure"/>
    <feature var="http://jabber.org/protocol/pubsub"/>
    <feature var="http://jabber.org/protocol/pubsub#publisher-affiliation"/>
    <feature var="http://jabber.org/protocol/pubsub#access-open"/>
    <feature var="http://jabber.org/protocol/pubsub#retrieve-affiliations"/>
    <feature var="jabber:iq:version"/>
    <feature var="http://jabber.org/protocol/pubsub#retract-items"/>
    <feature var="urn:xmpp:time"/>
    <feature var="http://jabber.org/protocol/pubsub#manage-subscriptions"/>
    <feature var="jabber:iq:privacy"/>
    <feature var="jabber:iq:last"/>
    <feature var="http://jabber.org/protocol/commands"/>
    <feature var="http://jabber.org/protocol/offline"/>
    <feature var="urn:xmpp:carbons:2"/>
    <feature var="http://jabber.org/protocol/address"/>
    <feature var="http://jabber.org/protocol/pubsub#publish"/>
    <feature var="http://jabber.org/protocol/pubsub#collections"/>
    <feature var="http://jabber.org/protocol/pubsub#retrieve-subscriptions"/>
    <feature var="http://jabber.org/protocol/disco#info"/>
    <feature var="jabber:iq:private"/>
    <feature var="http://jabber.org/protocol/rsm"/>
  </query>
</iq>

1.2 查询发布订阅中的某一个持久化的叶子节点

<?xml version="1.0" encoding="utf-8"?>

<iq to="pubsub.pc-20170308pkrs" id="3EV56-9" type="get">
  <query xmlns="http://jabber.org/protocol/disco#info" node="/BAGGL/GJXX/LCGJ"></query>
</iq>

返回

<?xml version="1.0" encoding="utf-8"?>

<iq type="result" id="3EV56-9" from="pubsub.pc-20170308pkrs" to="gm@pc-20170308pkrs/pc">
  <query xmlns="http://jabber.org/protocol/disco#info" node="/BAGGL/GJXX/LCGJ">
    <identity category="pubsub" type="leaf"/>
    <feature var="http://jabber.org/protocol/pubsub"/>
    <feature var="http://jabber.org/protocol/disco#info"/>
    <x xmlns="jabber:x:data" type="result">
      <field var="FORM_TYPE" type="hidden">
        <value>http://jabber.org/protocol/pubsub#meta-data</value>
      </field>
      <field var="pubsub#title" type="text-single" label="Short name for the node">
        <value>流程告警</value>
      </field>
      <field var="pubsub#description" type="text-single" label="Description of the node">
        <value></value>
      </field>
      <field var="pubsub#node_type" type="text-single" label="Whether the node is a leaf (default) or a collection">
        <value>leaf</value>
      </field>
      <field var="pubsub#collection" type="text-single" label="The collection with which a node is affiliated."/>
      <field var="pubsub#subscribe" type="boolean" label="Allow subscriptions to node">
        <value>1</value>
      </field>
      <field var="pubsub#subscription_required" type="boolean" label="New subscriptions require configuration">
        <value>0</value>
      </field>
      <field var="pubsub#deliver_payloads" type="boolean" label="Deliver payloads with event notifications">
        <value>1</value>
      </field>
      <field var="pubsub#notify_config" type="boolean" label="Notify subscribers when the node configuration changes">
        <value>1</value>
      </field>
      <field var="pubsub#notify_delete" type="boolean" label="Notify subscribers when the node is deleted">
        <value>1</value>
      </field>
      <field var="pubsub#notify_retract" type="boolean" label="Notify subscribers when items are removed from the node">
        <value>1</value>
      </field>
      <field var="pubsub#presence_based_delivery" type="boolean" label="Only deliver notifications to available users">
        <value>0</value>
      </field>
      <field var="pubsub#type" type="text-single" label="Type of payload data to be provided at this node">
        <value></value>
      </field>
      <field var="pubsub#body_xslt" type="text-single" label="Message body XSLT">
        <value>/BAGGL/GJXX/LCGJ</value>
      </field>
      <field var="pubsub#dataform_xslt" type="text-single" label="Payload XSLT">
        <value></value>
      </field>
      <field var="pubsub#access_model" type="list-single" label="Specify who may subscribe and retrieve items">
        <option>
          <value>authorize</value>
        </option>
        <option>
          <value>open</value>
        </option>
        <option>
          <value>presence</value>
        </option>
        <option>
          <value>roster</value>
        </option>
        <option>
          <value>whitelist</value>
        </option>
        <value>open</value>
      </field>
      <field var="pubsub#publish_model" type="list-single" label="Publisher model">
        <option>
          <value>publishers</value>
        </option>
        <option>
          <value>subscribers</value>
        </option>
        <option>
          <value>open</value>
        </option>
        <value>open</value>
      </field>
      <field var="pubsub#roster_groups_allowed" type="list-multi" label="Roster groups allowed to subscribe"/>
      <field var="pubsub#contact" type="jid-multi" label="People to contact with questions"/>
      <field var="pubsub#language" type="text-single" label="Default language">
        <value>English</value>
      </field>
      <field var="pubsub#owner" type="jid-multi" label="Node owners">
        <value>admin@pc-20170308pkrs</value>
      </field>
      <field var="pubsub#publisher" type="jid-multi" label="Node publishers"/>
      <field var="pubsub#itemreply" type="list-single" label="Select entity that should receive replies to items">
        <option>
          <value>owner</value>
        </option>
        <option>
          <value>publisher</value>
        </option>
        <value>owner</value>
      </field>
      <field var="pubsub#replyroom" type="jid-multi" label="Multi-user chat room to which replies should be sent"/>
      <field var="pubsub#replyto" type="jid-multi" label="Users to which replies should be sent"/>
      <field var="pubsub#send_item_subscribe" type="boolean" label="Send items to new subscribers">
        <value>1</value>
      </field>
      <field var="pubsub#persist_items" type="boolean" label="Persist items to storage">
        <value>1</value>
      </field>
      <field var="pubsub#max_items" type="text-single" label="Max number of items to persist">
        <value>100000</value>
      </field>
      <field var="pubsub#max_payload_size" type="text-single" label="Max payload size in bytes">
        <value>5120</value>
      </field>
    </x>
  </query>
</iq>

1.3 订阅消息到达

<?xml version="1.0" encoding="utf-8"?>

<message from="pubsub.pc-20170308pkrs" to="gm@pc-20170308pkrs" id="N5K5HEvD">
  <event xmlns="http://jabber.org/protocol/pubsub#event">
    <items node="/BAGGL/GJXX/LCGJ">
      <item id="1528350475613">
        <pubmessage xmlns="pub:message">
          <topic>/BAGGL/GJXX/LCGJ</topic>
          <messageid>1528350475613</messageid>
          <content>流程告警193</content>
        </pubmessage>
      </item>
    </items>
  </event>
  <headers xmlns="http://jabber.org/protocol/shim">
    <header name="SubID">A5OJTdo105AM4hNOhMeNRvKiVelT2CAMCGb9NYxC</header>
  </headers>
  <delay xmlns="urn:xmpp:delay" stamp="2018-06-07T05:47:55.676Z" from="pc-20170308pkrs"></delay>
</message>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值