Skip to content

Commit

Permalink
cached and reused udp datagram packet.
Browse files Browse the repository at this point in the history
  • Loading branch information
m4gr3d committed May 27, 2015
1 parent 77ef1b4 commit e392484
Showing 1 changed file with 23 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ public abstract class UdpConnection extends MavLinkConnection {

private int hostPort;
private InetAddress hostAdd;
private DatagramPacket sendPacket;
private DatagramPacket receivePacket;

private void getUdpStream() throws IOException {
final DatagramSocket socket = new DatagramSocket(serverPort);
Expand Down Expand Up @@ -46,8 +48,14 @@ public final void sendBuffer(byte[] buffer) throws IOException {
try {
if (hostAdd != null) { // We can't send to our sister until they
// have connected to us
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, hostAdd, hostPort);
socket.send(packet);
if(sendPacket == null)
sendPacket = new DatagramPacket(buffer, buffer.length, hostAdd, hostPort);
else{
sendPacket.setData(buffer, 0, buffer.length);
sendPacket.setAddress(hostAdd);
sendPacket.setPort(hostPort);
}
socket.send(sendPacket);
}
} catch (Exception e) {
e.printStackTrace();
Expand All @@ -65,15 +73,19 @@ public void sendBuffer(InetAddress targetAddr, int targetPort, byte[] buffer) th

@Override
public final int readDataBlock(byte[] readData) throws IOException {
final DatagramSocket socket = socketRef.get();
if(socket == null)
return 0;

DatagramPacket packet = new DatagramPacket(readData, readData.length);
socket.receive(packet);
hostAdd = packet.getAddress();
hostPort = packet.getPort();
return packet.getLength();
final DatagramSocket socket = socketRef.get();
if (socket == null)
return 0;

if (receivePacket == null)
receivePacket = new DatagramPacket(readData, readData.length);
else
receivePacket.setData(readData);

socket.receive(receivePacket);
hostAdd = receivePacket.getAddress();
hostPort = receivePacket.getPort();
return receivePacket.getLength();
}

@Override
Expand Down

0 comments on commit e392484

Please sign in to comment.