1515import java .net .UnknownHostException ;
1616import java .util .Map ;
1717import java .util .concurrent .ConcurrentHashMap ;
18+ import java .util .concurrent .ExecutorService ;
19+ import java .util .concurrent .Executors ;
20+ import java .util .concurrent .Future ;
1821
1922import static com .tradle .react .UdpSenderTask .OnDataSentListener ;
2023
@@ -25,13 +28,15 @@ public final class UdpSocketClient implements UdpReceiverTask.OnDataReceivedList
2528 private final OnDataReceivedListener mReceiverListener ;
2629 private final OnRuntimeExceptionListener mExceptionListener ;
2730
31+ private ExecutorService executor = Executors .newSingleThreadExecutor ();
32+
2833 private UdpReceiverTask mReceiverTask ;
2934
3035 private final Map <UdpSenderTask , Callback > mPendingSends ;
3136 private DatagramSocket mSocket ;
3237 private boolean mIsMulticastSocket = false ;
3338
34- public UdpSocketClient (OnDataReceivedListener receiverListener , OnRuntimeExceptionListener exceptionListener ) {
39+ public UdpSocketClient (OnDataReceivedListener receiverListener , OnRuntimeExceptionListener exceptionListener ) {
3540 this .mReceiverListener = receiverListener ;
3641 this .mExceptionListener = exceptionListener ;
3742 this .mPendingSends = new ConcurrentHashMap <>();
@@ -125,18 +130,15 @@ public void send(String base64String, Integer port, String address, @Nullable Ca
125130
126131 byte [] data = Base64 .decode (base64String , Base64 .NO_WRAP );
127132
128- UdpSenderTask task = new UdpSenderTask (mSocket , this );
129- UdpSenderTask .SenderPacket packet = new UdpSenderTask .SenderPacket ();
130- packet .data = data ;
131- packet .socketAddress = new InetSocketAddress (InetAddress .getByName (address ), port );
133+ UdpSenderTask task = new UdpSenderTask (mSocket , this , new InetSocketAddress (InetAddress .getByName (address ), port ), data );
132134
133135 if (callback != null ) {
134136 synchronized (mPendingSends ) {
135137 mPendingSends .put (task , callback );
136138 }
137139 }
138140
139- task . execute ( packet );
141+ executor . submit ( task );
140142 }
141143
142144 /**
@@ -157,6 +159,9 @@ public void close() {
157159 mReceiverTask .terminate ();
158160 }
159161
162+ // stop pending send tasks
163+ executor .shutdownNow ();
164+
160165 // close the socket
161166 if (mSocket != null && !mSocket .isClosed ()) {
162167 mSocket .close ();
0 commit comments