java - Receive UDP packets fast -
java - Receive UDP packets fast -
i have udp listener thread, looped , calls method 1 time packet received. works fine, method not beingness called when more 1 packet arrives after first one.
two packets send 1 time after another, first 2 bytes long, sec 3 bytes long. receive() method tends fired when sec packet arrives.
here udp listener class:
public class udplistener extends thread{ private boolean running = true; byte[] info = new byte[1500]; datagrampacket packet = new datagrampacket(data, data.length); public void run() { log.v("mr", "runs"); seek { while(running) { log.v("mr", "listening... "); socket.receive(packet); log.v("mr", "received data: " + packet.getdata()[0] + "; length: " + packet.getlength()); device.post(new runnable() { public void run() { device.receive(packet.getdata(), packet.getdata().length); } }); } } grab (throwable e) { e.printstacktrace(); log.v("mr", "failed receiving"); } } }
here device.receive() method:
public final void receive(byte[] indata, int length) { info = indata; datalength = length; log.v("mr", "receive(): data: +" + data[0] + "; length: " + string.valueof(data.length)); }
here part of log result:
10-18 17:24:34.393 received data: 79; length: 3 10-18 17:24:34.393 listening... 10-18 17:24:34.393 receive(): data: +79; length: 1500 10-18 17:24:34.393 receive(): data: +79; length: 1500 10-18 17:24:34.413 received data: 6; length: 2 10-18 17:24:34.413 listening... 10-18 17:24:34.413 received data: 79; length: 3 10-18 17:24:34.413 listening... 10-18 17:24:34.413 receive(): data: +79; length: 1500 10-18 17:24:34.413 receive(): data: +79; length: 1500 10-18 17:24:34.423 received data: 6; length: 2 10-18 17:24:34.423 listening...
as can seen packets coming in, receive() called more sec (length: 3) packet.
'device' custom view, receive() method. tried handler , runonuithread() runnable same results. assume ui thread can't updated fast or similar.
also, why packets real length in thread log , 1500 bytes in resume() log? supposed same packet passed.
i saw there 80+ views of question. solution utilize handler send message ui , re-initialize data[] array , datagrampacket before new packet comes.
the working code is:
public static class udplistener extends thread{ private boolean running = true; message msg; byte[] data; datagrampacket packet; public void run() { seek { while(running) { info = new byte[1500]; packet = new datagrampacket(data, data.length); //blocks , waits packet socket.receive(packet); //send packet message ui msg = udpreceivehandler.obtainmessage(); msg.obj = packet; udpreceivehandler.sendmessage(msg); } } grab (throwable e) { e.printstacktrace(); } } }
java android udp
Comments
Post a Comment