我有以下Java while循环:
while(true){
byte buffer[] = new byte[MAX_PDU_SIZE];
packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
Pdu pdu = pduFactory.createPdu(packet.getData());
System.out.print("Got PDU of type: " + pdu.getClass().getName());
if(pdu instanceof EntityStatePdu){
EntityID eid = ((EntityStatePdu)pdu).getEntityID();
Vector3Double position = ((EntityStatePdu)pdu).getEntityLocation();
System.out.print(" EID:[" + eid.getSite() + ", " + eid.getApplication() + ", " + eid.getEntity() + "] ");
System.out.print(" Location in DIS coordinates: [" + position.getX() + ", " + position.getY() + ", " + position.getZ() + "]");
}
System.out.println();
}
}while循环的预期功能是捕获通过网络发送的任何PDU,并显示有关它们的信息。
当我运行代码时,我得到了我在控制台中想要的输出--至少在最初.但是,当它返回了一些PDU的信息后,我在控制台中看到了一个错误(不记得它现在说了什么--但我认为这可能是因为它试图捕获PDU,而没有发送PDU)。
我已经尝试修改我的代码,以考虑到当PDU试图通过下面的try- catch循环包围代码来捕获有关PDU的信息时,它可能不会通过网络接收到PDU:
try{
socket = new MulticastSocket(EspduSender.PORT);
address = InetAddress.getByName(EspduSender.DEFAULT_MULTICAST_GROUP);
socket.joinGroup(address);
while(true){
byte buffer[] = new byte[MAX_PDU_SIZE];
packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
Pdu pdu = pduFactory.createPdu(packet.getData());
System.out.print("Got PDU of type: " + pdu.getClass().getName());
if(pdu instanceof EntityStatePdu){
EntityID eid = ((EntityStatePdu)pdu).getEntityID();
Vector3Double position = ((EntityStatePdu)pdu).getEntityLocation();
System.out.print(" EID:[" + eid.getSite() + ", " + eid.getApplication() + ", " + eid.getEntity() + "] ");
System.out.print(" Location in DIS coordinates: [" + position.getX() + ", " + position.getY() + ", " + position.getZ() + "]");
}
System.out.println();
}
}
catch(Exception e){
System.out.println(e);
System.out.println("This is where the error is being generated");
}但是,当我现在运行这个代码时-它仍然显示它捕获的第一个x个DIS数据包(每次我运行代码时x都会改变),然后给我一个java.lang.NullPointerException。据我所知,这要么是因为代码捕获的PDU不包含任何信息(即“空”PDU),要么是因为它试图在没有通过网络发送PDU的情况下接收PDU。
我如何让代码“跳过”没有接收到PDU的情况,然后继续运行呢?或者我还应该做些什么来消除这个错误呢?
发布于 2014-04-14 14:23:40
这可能无法解决您的问题(直到您放置堆栈跟踪时才知道),但是您可以在使用pdu之前检查它是否为null。
while(true){
byte buffer[] = new byte[MAX_PDU_SIZE];
packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
Pdu pdu = pduFactory.createPdu(packet.getData());
if (pdu != null) {
System.out.print("Got PDU of type: " + pdu.getClass().getName());
if(pdu instanceof EntityStatePdu){
EntityID eid = ((EntityStatePdu)pdu).getEntityID();
Vector3Double position = ((EntityStatePdu)pdu).getEntityLocation();
System.out.print(" EID:[" + eid.getSite() + ", " + eid.getApplication() + ", " + eid.getEntity() + "] ");
System.out.print(" Location in DIS coordinates: [" + position.getX() + ", " + position.getY() + ", " + position.getZ() + "]");
}
System.out.println();
}
}如果您得到堆栈跟踪,我可以根据您的实际问题更改此选项。
发布于 2014-04-14 14:55:46
您的代码看起来非常好,除了下面缺少的行。
if (pdu != null) {
//execute this
}https://stackoverflow.com/questions/23062454
复制相似问题