简体   繁体   English

UDP接收器代码仅接收一个数据包

[英]UDP Receiver code only receiving one packet

Th following code only receives on packet of data. 以下代码仅在数据包上接收。 I have sent different sizes of data to see if data is being received on the receiver. 我已发送了不同大小的数据,以查看接收器上是否正在接收数据。 I only get the first packet and I do not see any other packets. 我只得到第一个数据包,而看不到其他任何数据包。 What could be the cause of the missing packets. 丢失数据包的原因可能是什么。 Since I am receiving 12 bytes every time. 由于我每次接收12个字节。 Do I need to clear the buffer or make it larger. 我是否需要清除缓冲区或使其更大。 What practices should I follow. 我应该遵循什么做法。

import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class Reciever {
  public static void main(String[] args) {
    try {
      DatagramSocket s = new DatagramSocket(2010);
      byte[] data = new byte[12];
      DatagramPacket p = new DatagramPacket(data, 12);
      s.receive(p);
      System.out.println("got packet");
      ByteBuffer bb = ByteBuffer.allocate(12).order(ByteOrder.LITTLE_ENDIAN);
      bb.put(data);
      bb.rewind();
      System.out.println(bb.getFloat());
      System.out.println(bb.getFloat());
      System.out.println(bb.getFloat());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

You receive only one UDP packet because you call receive only once and then exit. 您仅收到一个UDP数据包,因为调用仅receive一次,然后退出。 If more than one packet is sent you will receive one and the others are dropped and lost forever. 如果发送了多个数据包,您将收到一个数据包,而其他的数据包将永远丢失并丢失。

Add a loop to receive more than one packet: 添加一个循环以接收多个数据包:

try {
    DatagramSocket s = new DatagramSocket(2010);
    byte[] data = new byte[12];
    DatagramPacket p = new DatagramPacket(data, 12);
    while (true) {
        s.receive(p);
        System.out.println("got packet");
        ByteBuffer bb = ByteBuffer.allocate(12).order(ByteOrder.LITTLE_ENDIAN);
        bb.put(data);
        bb.rewind();
        System.out.println(bb.getFloat());
        System.out.println(bb.getFloat());
        System.out.println(bb.getFloat());
    }
} catch (IOException e) {
  e.printStackTrace();
}

I got it working by adding a while loop and moving the DatagramSocket s = new DatagramSocket(2010); 我通过添加一个while循环并移动DatagramSocket s = new DatagramSocket(2010)使其工作。 byte[] data = new byte[12]; 字节[]数据=新字节[12]; outside the loop 循环外

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM