【问题标题】:Why is my program hanging on a system.out.print of DatagramPacket.getData()为什么我的程序挂在 DatagramPacket.getData() 的 system.out.print 上
【发布时间】:2012-11-19 03:07:02
【问题描述】:
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));
}

我们正在尝试从queue(数据包列表)中获取所有数据,并将它们全部放入一个字符串中。

但每当它到达第二个println(与它下面的行相同)时,程序就会挂起并且不做任何事情。

没有getData() 打印工作。例如。

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

此外,每当我将数据包添加到队列中时,我都会立即打印队列中的最后一个数据包,这样就可以了。

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

【问题讨论】:

  • 猜,还没有来自cold^W,网络的数据
  • 我已经收到数据包并在将其添加到队列之前将其打印,但现在当我们检索它时,它什么也不做。它不返回null,它只是挂起程序。
  • 进行线程转储,然后检查调用getData的线程卡在哪里。

标签: java udp linked-list packet datagram


【解决方案1】:

我不确定DatagramPacket 类,但这肯定解决了与String 操作和LinkedList.get 相关的一些性能问题。可能只是你的程序运行得很慢?

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();

如果你尝试这个会怎样:

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()));
    }
  }
}

【讨论】:

  • 问题不在于性能,程序挂在第一个getData()
  • 两者。我把打印件放进去测试,所以从技术上讲,第一个说“这不打印”
  • 嗯,很明显,问题不在于您发布的代码 sn-p,而在于网络通信。不过,我仍然会进行这些已发布的更改:)
  • 我在队列中添加一个数据包后,立即打印出队列中的最后一个数据包,应该是我刚刚添加的那个,确实如此。我添加了用于添加到原始帖子的代码。
猜你喜欢
  • 2017-11-15
  • 2015-07-09
  • 1970-01-01
  • 2020-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-18
相关资源
最近更新 更多