0
LinkedList<DatagramPacket> queue = new LinkedList<DatagramPacket>();

for (int i = 0; i < queue.size(); i++)
{
    System.out.println("1: This prints.");
    System.out.println("2: This doesn't: " + new String(queue.get(i).getData()));
    int start = (new String(queue.get(i).getData())).indexOf("\r\n") + "\r\n".length();
    data.concat(new String(queue.get(i).getData()).substring(start));
}

We're trying to take all the data from queue, the list of packets, and put them all into one string.

But whenever it gets to the 2nd println (which is the same as the line below it) the program hangs and doesn't do anything.

Without the getData() the print works. eg.

System.out.printlin("2: This doesn't: " +  new String(queue.get(i)));

Also, whenever I add a packet to the queue, I immediately print the last packet in the queue, and that works.

public void addPacket(DatagramPacket additional)
{
    queue.add(additional);
    System.out.println("1: " + new String(queue.getLast().getData()));
}

1 Answers1

0

I'm not sure about the DatagramPacket class, but this certainly fixes some performance problems related to String manipulation and LinkedList.get. It might just be that your program runs really slowly?

StringBuilder dataBuilder = new StringBuilder(); 
Iterator<DatagramPacket> queueIter = queue.iterator();
while(queueIter.hasNext()) {
  DatagramPacket next = queueIter.next();
  System.out.println("1: This prints.");
  System.out.println("2: This doesn't: " + new String(next.getData()));
  int start = (new String(next.getData())).indexOf("\r\n") + "\r\n".length();
  dataBuilder.append(new String(next.getData()).substring(start));
}
data = dataBuilder.toString();

What if you tried this:

public class Foo {
  // instead of LinkedList<DatagramPacket>
  public LinkedList<String> queue = new LinkedList<String>(); 
  public void addPacket(DatagramPacket additional) {
      queue.add(new String(additional.getData()));
    }
  }
}
durron597
  • 31,968
  • 17
  • 99
  • 158
  • The problem isn't with the performance, the program hangs on the very first `getData()`. –  Nov 30 '12 at 21:01
  • Both. I put the print in to test, so technically the first one that says "This doesn't print" –  Nov 30 '12 at 21:07
  • Well, clearly the problem is not your posted code snippet then, it's something about the network communications. I would still make these posted changes, though :) – durron597 Nov 30 '12 at 21:09
  • After I add a packet to the queue, I immediately print out the last packet in the queue, which should be the one I just added, and it is. I added the code for adding to the original post. –  Nov 30 '12 at 21:11