powered by Jive Software

sendPacket

Hi!

I’m trying to send a packet to a number of users that i have stored in an

arraylist. to do this i do something like

for (String user : userlist) {

packet.setTo(user);

connection.sendPacket(packet);

}

The problem is that this approach doesnt work. Suppose there are 4

users in the userlist. Then, by checking the smack debugger, i can see that 4

packets are sent. So far so good. However of the 4 packets that are sent 2 or 3

of them are sent to the same person and so a few in the list are not sent any

packet at all. Why does this happen? I have tried using a synchronised

block on packet around the loop but the outcome is the same. I have tried

adding a thread sleep after each packet and this works sometimes but is not

reliable. The below post had the same issue but no resolution was posted.

Would anyone have any idea how to overcome this issue?

Thanks for your time

Steven

Hi,

When you call connection.sendPacket(packet) your packet is not necessarily sent immediately. It is actually added to a queue and then scheduled to be sent to the server by another thread so that your code doesn’t block. So let’s unroll the loop and consider the following example of what is probably happening:

packet.setTo(“user1”);

connection.sendPacket(packet); // Now the queue has 1 packet set for user1

packet.setTo(“user2”);

connection.sendPacket(packet); // Now the queue has 2 packets, but since both of them are the same instance, both are now set to user2

packet.setTo(“user3”);

connection.sendPacket(packet); // Now the queue has 3 copies of the same packet and all are now set for user3

  • The packet writer thread now wakes up, sends those 3 copies of the packet to the server, and clears the queue

packet.setTo(“user4”);

connection.sendPacket(packet); // Now the queue has 1 packet set for user4

  • The packet writer thread now wakes up and sends the packet to user4

So as you can see, due to the background sending thread, whether or not your code works depends on when the thread is given CPU time to process the packets. Whenever I needed to send out a packet to many users, I just created a new packet for each send and never had any problems.

Chris

Hi Chris,

I changed my code so that i create a new packet each time, as you suggested, and now all is completly fine.

Thanks loads for the explanation and advice

Steven