用smack做一个xmpp客户端似乎是一件很简单的事情。但是前几天发现的一个bug,还是让我思考了很多。
用smack建立一个xmpp connection。然后在connection 上注册了一个PacketListener。
但是程序里面在一个for循环里面去new PakcetListener,并把listener注册到connection上面。这样导致的结果就是
smack客户端收到许多相同的IQ response。
如果稍微看一下smack的源代码就明白问题出在哪里。
smack connection class:
/**
* Registers a packet listener with this connection. A packet filter determines
* which packets will be delivered to the listener. If the same packet listener
* is added again with a different filter, only the new filter will be used.
*
* @param packetListener the packet listener to notify of new received packets.
* @param packetFilter the packet filter to use.
*/
public void addPacketListener(PacketListener packetListener, PacketFilter packetFilter) {
if (packetListener == null) {
throw new NullPointerException("Packet listener is null.");
}
ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter);
recvListeners.put(packetListener, wrapper);
}
/**
* List of PacketListeners that will be notified when a new packet was received.
*/
protected final Map<PacketListener, ListenerWrapper> recvListeners =
new ConcurrentHashMap<PacketListener, ListenerWrapper>();
看完上面这两段代码,就知道了。如果重复注册listener。其实就意味着一个packet会被notify多次。
程序就回出现一些奇怪的现象。