Receive the latest UDP packet in C# -


i'm using unity visualize simulation data simulation being sent via udp packets simulink. problem i'm having stems rate @ simulink sends out udp packets , rate @ script in unity tries receive data udp client.

for unity script, create thread executes simple function while loop , sleeps same amount of time takes client timeout (which arbitrarily set me):

public void start() {     //  setup listener.     this.msenderaddress = ipaddress.parse("127.0.0.1");     this.msender = new ipendpoint(this.msenderaddress, 30001);      //  setup background udp listener thread.     this.mreceivethread = new thread(new threadstart(receivedata));     this.mreceivethread.isbackground = true;     this.mreceivethread.start(); }  //  function receive udp data. private void receivedata() {     try {         //  setup udp client.         this.mclient = new udpclient(30001);         this.mclient.client.receivetimeout = 250;          //  while thread still alive.         while(thread.currentthread.isalive) {             try {                 //  grab data.                 byte[] data = this.mclient.receive(ref this.msender);                  //  convert data bytes doubles.                 double[] converteddata = new double[data.length / 8];                 for(int ii = 0; ii < converteddata.length; ii++)                     converteddata[ii] = bitconverter.todouble(data, 8 * ii);                  //  whatever data                  //  sleep thread.                 thread.sleep(this.mclient.client.receivetimeout);             } catch(socketexception e) {                 continue;             }         }     } catch(exception e) {         debug.log(e.tostring());     } } 

here, if timeout / sleep time greater difference in time simulink sends out udp packet, visualization fall behind simulation because read next packet sent out , not last packet sent out. regarding packets queue.

is there anyway data last packet received? know there @ least 1 way around this, because if use rate transfer block set equal or greater sample time udpclient timeout work; i'd make more robust that.

since packets contain full information state of simulation (position, orientation, time, etc...) doesn't matter if never use data intermediate packets; long up-to-date data, last packet.

udp unreliable , packets not guaranteed received in same order sent. suggestion use tcp or put sort of sequence number in packets headers , keep reading udp packets , select newest packets.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -