1
0
Fork 0
mirror of https://github.com/vanitasvitae/Smack.git synced 2025-09-12 18:49:39 +02:00

SMACK-412 Split the ping implementation to a server ping to replace keepalive and a simplified ping manager for manual pings of other entities.

git-svn-id: http://svn.igniterealtime.org/svn/repos/smack/branches/smack_3_3_0@13569 b35dd754-fafc-0310-a699-88a17e54d16e
This commit is contained in:
rcollier 2013-03-19 02:37:36 +00:00
parent a55b54f20b
commit aab1dcdabe
19 changed files with 749 additions and 651 deletions

View file

@ -178,12 +178,12 @@ public abstract class Connection {
protected SmackDebugger debugger = null;
/**
* The Reader which is used for the {@see debugger}.
* The Reader which is used for the debugger.
*/
protected Reader reader;
/**
* The Writer which is used for the {@see debugger}.
* The Writer which is used for the debugger.
*/
protected Writer writer;

View file

@ -40,18 +40,11 @@ import java.util.concurrent.BlockingQueue;
class PacketWriter {
private Thread writerThread;
private Thread keepAliveThread;
private Writer writer;
private XMPPConnection connection;
private final BlockingQueue<Packet> queue;
volatile boolean done;
/**
* Timestamp when the last stanza was sent to the server. This information is used
* by the keep alive process to only send heartbeats when the connection has been idle.
*/
private long lastActive = System.currentTimeMillis();
/**
* Creates a new packet writer with the specified connection.
*
@ -117,25 +110,6 @@ class PacketWriter {
writerThread.start();
}
/**
* Starts the keep alive process. A white space (aka heartbeat) is going to be
* sent to the server every 30 seconds (by default) since the last stanza was sent
* to the server.
*/
void startKeepAliveProcess() {
// Schedule a keep-alive task to run if the feature is enabled. will write
// out a space character each time it runs to keep the TCP/IP connection open.
int keepAliveInterval = SmackConfiguration.getKeepAliveInterval();
if (keepAliveInterval > 0) {
KeepAliveTask task = new KeepAliveTask(keepAliveInterval);
keepAliveThread = new Thread(task);
task.setThread(keepAliveThread);
keepAliveThread.setDaemon(true);
keepAliveThread.setName("Smack Keep Alive (" + connection.connectionCounterValue + ")");
keepAliveThread.start();
}
}
void setWriter(Writer writer) {
this.writer = writer;
}
@ -149,9 +123,6 @@ class PacketWriter {
synchronized (queue) {
queue.notifyAll();
}
// Interrupt the keep alive thread if one was created
if (keepAliveThread != null)
keepAliveThread.interrupt();
}
/**
@ -193,10 +164,9 @@ class PacketWriter {
if (packet != null) {
synchronized (writer) {
writer.write(packet.toXML());
writer.flush();
if (queue.isEmpty()) {
writer.flush();
// Keep track of the last time a stanza was sent to the server
lastActive = System.currentTimeMillis();
}
}
}
@ -268,54 +238,4 @@ class PacketWriter {
writer.write(stream.toString());
writer.flush();
}
/**
* A TimerTask that keeps connections to the server alive by sending a space
* character on an interval.
*/
private class KeepAliveTask implements Runnable {
private int delay;
private Thread thread;
public KeepAliveTask(int delay) {
this.delay = delay;
}
protected void setThread(Thread thread) {
this.thread = thread;
}
public void run() {
try {
// Sleep a minimum of 15 seconds plus delay before sending first heartbeat. This will give time to
// properly finish TLS negotiation and then start sending heartbeats.
Thread.sleep(15000 + delay);
}
catch (InterruptedException ie) {
// Do nothing
}
while (!done && keepAliveThread == thread) {
synchronized (writer) {
// Send heartbeat if no packet has been sent to the server for a given time
if (System.currentTimeMillis() - lastActive >= delay) {
try {
writer.write(" ");
writer.flush();
}
catch (Exception e) {
// Do nothing
}
}
}
try {
// Sleep until we should write the next keep-alive.
Thread.sleep(delay);
}
catch (InterruptedException ie) {
// Do nothing
}
}
}
}
}

View file

@ -58,11 +58,6 @@ public final class SmackConfiguration {
private static int localSocks5ProxyPort = 7777;
private static int packetCollectorSize = 5000;
/**
* defaultPingInterval (in seconds)
*/
private static int defaultPingInterval = 1800; // 30 min (30*60)
/**
* This automatically enables EntityCaps for new connections if it is set to true
*/
@ -117,9 +112,6 @@ public final class SmackConfiguration {
else if (parser.getName().equals("packetCollectorSize")) {
packetCollectorSize = parseIntProperty(parser, packetCollectorSize);
}
else if (parser.getName().equals("defaultPingInterval")) {
defaultPingInterval = parseIntProperty(parser, defaultPingInterval);
}
else if (parser.getName().equals("autoEnableEntityCaps")) {
autoEnableEntityCaps = Boolean.parseBoolean(parser.nextText());
}
@ -319,24 +311,6 @@ public final class SmackConfiguration {
SmackConfiguration.localSocks5ProxyPort = localSocks5ProxyPort;
}
/**
* Returns the default ping interval (seconds)
*
* @return
*/
public static int getDefaultPingInterval() {
return defaultPingInterval;
}
/**
* Sets the default ping interval (seconds). Set it to '-1' to disable the periodic ping
*
* @param defaultPingInterval
*/
public static void setDefaultPingInterval(int defaultPingInterval) {
SmackConfiguration.defaultPingInterval = defaultPingInterval;
}
/**
* Check if Entity Caps are enabled as default for every new connection
* @return

View file

@ -650,10 +650,6 @@ public class XMPPConnection extends Connection {
// Make note of the fact that we're now connected.
connected = true;
// Start keep alive process (after TLS was negotiated - if available)
packetWriter.startKeepAliveProcess();
if (isFirstInitialization) {
// Notify listeners that a new connection has been established
for (ConnectionCreationListener listener : getConnectionCreationListeners()) {

View file

@ -0,0 +1,27 @@
/**
* Copyright 2012 Florian Schmaus
*
* All rights reserved. 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.
*/
package org.jivesoftware.smack.ping;
/**
* Defines the callback used whenever the server ping fails.
*/
public interface PingFailedListener {
/**
* Called when the server ping fails.
*/
void pingFailed();
}

View file

@ -0,0 +1,285 @@
/**
* Copyright 2012-2013 Florian Schmaus
*
* All rights reserved. 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.
*/
package org.jivesoftware.smack.ping;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionCreationListener;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.IQTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.IQ.Type;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.ping.packet.Ping;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
/**
* Using an implementation of <a href="http://www.xmpp.org/extensions/xep-0199.html">XMPP Ping (XEP-0199)</a>. This
* class provides keepalive functionality with the server that will periodically "ping" the server to maintain and/or
* verify that the connection still exists.
* <p>
* The ping is done at the application level and is therefore protocol agnostic. It will thus work for both standard TCP
* connections as well as BOSH or any other transport protocol. It will also work regardless of whether the server
* supports the Ping extension, since an error response to the ping serves the same purpose as a pong.
*
* @author Florian Schmaus
*/
public class ServerPingManager {
public static final long PING_MINIMUM = 10000;
private static Map<Connection, ServerPingManager> instances = Collections
.synchronizedMap(new WeakHashMap<Connection, ServerPingManager>());
private static long defaultPingInterval = SmackConfiguration.getKeepAliveInterval();
private static ScheduledExecutorService periodicPingExecutorService = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
@Override
public Thread newThread(Runnable runnable) {
Thread pingThread = new Thread(runnable, "Smack Server Ping");
pingThread.setDaemon(true);
return pingThread;
}
});
static {
if (defaultPingInterval > 0) {
Connection.addConnectionCreationListener(new ConnectionCreationListener() {
public void connectionCreated(Connection connection) {
new ServerPingManager(connection);
}
});
}
}
private Connection connection;
private long pingInterval = SmackConfiguration.getKeepAliveInterval();
private Set<PingFailedListener> pingFailedListeners = Collections.synchronizedSet(new HashSet<PingFailedListener>());
private volatile ScheduledFuture<?> periodicPingTask;
private volatile long lastSuccessfulContact = -1;
/**
* Retrieves a {@link ServerPingManager} for the specified {@link Connection}, creating one if it doesn't already
* exist.
*
* @param connection
* The connection the manager is attached to.
* @return The new or existing manager.
*/
public synchronized static ServerPingManager getInstanceFor(Connection connection) {
ServerPingManager pingManager = instances.get(connection);
if (pingManager == null) {
pingManager = new ServerPingManager(connection);
}
return pingManager;
}
private ServerPingManager(Connection connection) {
ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection);
sdm.addFeature(Ping.NAMESPACE);
this.connection = connection;
init();
}
private void init() {
PacketFilter pingPacketFilter = new AndFilter(new PacketTypeFilter(Ping.class), new IQTypeFilter(Type.GET));
connection.addPacketListener(new PacketListener() {
/**
* Sends a Pong for every Ping
*/
public void processPacket(Packet packet) {
IQ pong = IQ.createResultIQ((Ping) packet);
connection.sendPacket(pong);
}
}, pingPacketFilter);
connection.addConnectionListener(new ConnectionListener() {
@Override
public void connectionClosed() {
stopPingServerTask();
}
@Override
public void connectionClosedOnError(Exception arg0) {
stopPingServerTask();
}
@Override
public void reconnectionSuccessful() {
schedulePingServerTask();
}
@Override
public void reconnectingIn(int seconds) {
}
@Override
public void reconnectionFailed(Exception e) {
}
});
// Listen for all incoming packets and reset the scheduled ping whenever
// one arrives.
connection.addPacketListener(new PacketListener() {
@Override
public void processPacket(Packet packet) {
// reschedule the ping based on this last server contact
lastSuccessfulContact = System.currentTimeMillis();
schedulePingServerTask();
}
}, null);
instances.put(connection, this);
schedulePingServerTask();
}
/**
* Sets the ping interval.
*
* @param pingInterval
* The new ping time interval in milliseconds.
*/
public void setPingInterval(long newPingInterval) {
if (newPingInterval < PING_MINIMUM)
newPingInterval = PING_MINIMUM;
if (pingInterval != newPingInterval) {
pingInterval = newPingInterval;
schedulePingServerTask();
}
}
/**
* Stops pinging the server. This cannot stop a ping that has already started, but will prevent another from being triggered.
* <p>
* To restart, call {@link #setPingInterval(long)}.
*/
public void stopPinging() {
pingInterval = -1;
stopPingServerTask();
}
/**
* Gets the ping interval.
*
* @return The ping interval in milliseconds.
*/
public long getPingInterval() {
return pingInterval;
}
/**
* Add listener for notification when a server ping fails.
*
* <p>
* Please note that this doesn't necessarily mean that the connection is lost, a slow to respond server could also
* cause a failure due to taking too long to respond and thus causing a reply timeout.
*
* @param listener
* The listener to be called
*/
public void addPingFailedListener(PingFailedListener listener) {
pingFailedListeners.add(listener);
}
/**
* Remove the listener.
*
* @param listener
* The listener to be removed.
*/
public void removePingFailedListener(PingFailedListener listener) {
pingFailedListeners.remove(listener);
}
/**
* Returns the time of the last successful contact with the server. (i.e. the last time any message was received).
*
* @return Time of last message or -1 if none has been received since manager was created.
*/
public long getLastSuccessfulContact() {
return lastSuccessfulContact;
}
/**
* Cancels any existing periodic ping task if there is one and schedules a new ping task if pingInterval is greater
* then zero.
*
* This is designed so only one executor is used for scheduling all pings on all connections. This results in only 1 thread used for pinging.
*/
private synchronized void schedulePingServerTask() {
stopPingServerTask();
if (pingInterval > 0) {
periodicPingTask = periodicPingExecutorService.schedule(new Runnable() {
@Override
public void run() {
Ping ping = new Ping();
PacketFilter responseFilter = new PacketIDFilter(ping.getPacketID());
final PacketCollector response = connection.createPacketCollector(responseFilter);
connection.sendPacket(ping);
if (!pingFailedListeners.isEmpty()) {
// Schedule a collector for the ping reply, notify listeners if none is received.
periodicPingExecutorService.schedule(new Runnable() {
@Override
public void run() {
Packet result = response.nextResult(1);
// Stop queuing results
response.cancel();
// The actual result of the reply can be ignored since we only care if we actually got one.
if (result == null) {
for (PingFailedListener listener : pingFailedListeners) {
listener.pingFailed();
}
}
}
}, SmackConfiguration.getPacketReplyTimeout(), TimeUnit.MILLISECONDS);
}
}
}, getPingInterval(), TimeUnit.MILLISECONDS);
}
}
private void stopPingServerTask() {
if (periodicPingTask != null) {
periodicPingTask.cancel(true);
periodicPingTask = null;
}
}
}

View file

@ -0,0 +1,39 @@
/**
* Copyright 2012 Florian Schmaus
*
* All rights reserved. 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.
*/
package org.jivesoftware.smack.ping.packet;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smackx.ping.PingManager;
public class Ping extends IQ {
public static final String NAMESPACE = "urn:xmpp:ping";
public static final String ELEMENT = "ping";
public Ping() {
}
public Ping(String to) {
setTo(to);
setType(IQ.Type.GET);
}
@Override
public String getChildElementXML() {
return "<" + ELEMENT + " xmlns=\'" + NAMESPACE + "\' />";
}
}

View file

@ -0,0 +1,32 @@
/**
* Copyright 2012 Florian Schmaus
*
* All rights reserved. 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.
*/
package org.jivesoftware.smack.ping.provider;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.ping.packet.Ping;
import org.jivesoftware.smack.provider.IQProvider;
import org.xmlpull.v1.XmlPullParser;
public class PingProvider implements IQProvider {
public IQ parseIQ(XmlPullParser parser) throws Exception {
// No need to use the ping constructor with arguments. IQ will already
// have filled out all relevant fields ('from', 'to', 'id').
return new Ping();
}
}

View file

@ -47,7 +47,7 @@ final public class SyncPacketSend
response.cancel();
if (result == null) {
throw new XMPPException("No response from server.");
throw new XMPPException("No response from " + packet.getTo());
}
else if (result.getError() != null) {
throw new XMPPException(result.getError());