Вопрос

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()));
}
Это было полезно?

Решение

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()));
    }
  }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top