Skip to content

Commit e392484

Browse files
committed
cached and reused udp datagram packet.
1 parent 77ef1b4 commit e392484

File tree

1 file changed

+23
-11
lines changed

1 file changed

+23
-11
lines changed

dependencyLibs/Core/src/org/droidplanner/core/MAVLink/connection/UdpConnection.java

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ public abstract class UdpConnection extends MavLinkConnection {
1616

1717
private int hostPort;
1818
private InetAddress hostAdd;
19+
private DatagramPacket sendPacket;
20+
private DatagramPacket receivePacket;
1921

2022
private void getUdpStream() throws IOException {
2123
final DatagramSocket socket = new DatagramSocket(serverPort);
@@ -46,8 +48,14 @@ public final void sendBuffer(byte[] buffer) throws IOException {
4648
try {
4749
if (hostAdd != null) { // We can't send to our sister until they
4850
// have connected to us
49-
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, hostAdd, hostPort);
50-
socket.send(packet);
51+
if(sendPacket == null)
52+
sendPacket = new DatagramPacket(buffer, buffer.length, hostAdd, hostPort);
53+
else{
54+
sendPacket.setData(buffer, 0, buffer.length);
55+
sendPacket.setAddress(hostAdd);
56+
sendPacket.setPort(hostPort);
57+
}
58+
socket.send(sendPacket);
5159
}
5260
} catch (Exception e) {
5361
e.printStackTrace();
@@ -65,15 +73,19 @@ public void sendBuffer(InetAddress targetAddr, int targetPort, byte[] buffer) th
6573

6674
@Override
6775
public final int readDataBlock(byte[] readData) throws IOException {
68-
final DatagramSocket socket = socketRef.get();
69-
if(socket == null)
70-
return 0;
71-
72-
DatagramPacket packet = new DatagramPacket(readData, readData.length);
73-
socket.receive(packet);
74-
hostAdd = packet.getAddress();
75-
hostPort = packet.getPort();
76-
return packet.getLength();
76+
final DatagramSocket socket = socketRef.get();
77+
if (socket == null)
78+
return 0;
79+
80+
if (receivePacket == null)
81+
receivePacket = new DatagramPacket(readData, readData.length);
82+
else
83+
receivePacket.setData(readData);
84+
85+
socket.receive(receivePacket);
86+
hostAdd = receivePacket.getAddress();
87+
hostPort = receivePacket.getPort();
88+
return receivePacket.getLength();
7789
}
7890

7991
@Override

0 commit comments

Comments
 (0)