usera
向 发送订阅请求userb
。执行以下代码后,只能在他的花名册列表usera
中看到,而不能看到. 这是为什么 ?userb
userb
首先调用函数userB
,然后从该函数userA
内部调用。我已经注册了一个packetListener
,userb
但令我惊讶的是它不起作用!我通过尝试打印一个语句来测试它,但我没有看到任何输出。所以监听器没有被执行。这可能是什么原因?
以下是以下代码中发生的情况:
userB ---activates packet listener-----> userA
| |
| |
| sends request to userB
| |
/ \ \ /
|--------------------<--------------------| |
public void userB() {
try {
final Connection connection = new XMPPConnection("localhost");
connection.connect();
connection.login("userb", "passb");
Roster r = connection.getRoster();
r.setSubscriptionMode(Roster.SubscriptionMode.manual);
PacketListener pListener = new PacketListener() {
@Override
public void processPacket(Packet packet) {
if(packet instanceof Presence) {
Presence presence =(Presence)packet;
if(presence.getType().equals(Presence.Type.subscribe)) {
System.out.println("Inside the first if statement");
Presence newP = new Presence(Presence.Type.subscribed);
newP.setMode(Presence.Mode.available);
newP.setTo(presence.getFrom());
connection.sendPacket(newP);
Presence subscription = new Presence(Presence.Type.subscribe);
subscription.setTo(presence.getFrom());
connection.sendPacket(subscription);
}
}
}
};
PacketFilter pFilter = new PacketFilter() {
@Override
public boolean accept(Packet packet) {
if(packet instanceof Presence) {
Presence presence = (Presence)packet;
if(presence.getType().equals(Presence.Type.subscribe)) {
System.out.println("Inside if statement");
return true;
}
}
return false;
}
};
connection.addPacketListener(pListener, pFilter);
Runnable runnable = new Runnable() {
@Override
public void run() {
userA();
}
};
new Thread(runnable).start();
//connection.disconnect();
}catch(Exception exc) {
exc.printStackTrace();
}
}
public void userA() {
try{
Connection connection = new XMPPConnection("localhost");
connection.connect();
connection.login("usera","passa");
Presence subscribe = new Presence(Presence.Type.subscribe);
subscribe.setTo("userb@localhost");
connection.sendPacket(subscribe);
connection.disconnect();
}catch(Exception exc) {
exc.printStackTrace();
}
}