3
3
import android .os .AsyncTask ;
4
4
import android .util .Log ;
5
5
6
- import java .io .BufferedReader ;
7
- import java .io .ByteArrayOutputStream ;
8
- import java .io .Closeable ;
9
6
import java .io .IOException ;
10
- import java .io .InputStream ;
11
- import java .io .InputStreamReader ;
12
- import java .io .OutputStream ;
13
- import java .io .PrintWriter ;
14
7
import java .net .DatagramPacket ;
15
8
import java .net .DatagramSocket ;
16
9
import java .net .InetSocketAddress ;
17
- import java .net .Socket ;
18
- import java .nio .channels .AsynchronousCloseException ;
19
- import java .nio .channels .ServerSocketChannel ;
20
- import java .nio .channels .SocketChannel ;
21
-
22
- import javax .inject .Inject ;
23
-
24
- import de .greenrobot .event .EventBus ;
25
- import events .ActivityEvent ;
26
10
27
11
import static com .github .dddpaul .netcat .NetCater .State .CONNECTED ;
28
12
import static com .github .dddpaul .netcat .NetCater .State .IDLE ;
29
- import static com .github .dddpaul .netcat .NetCater .State .LISTENING ;
30
13
31
14
public class UdpNetCat extends NetCat
32
15
{
33
16
private final String CLASS_NAME = getClass ().getSimpleName ();
34
17
35
18
private NetCatTask task ;
36
- private NetCatListener listener ;
37
- private ServerSocketChannel serverChannel ;
38
- private Closeable socket ;
39
- private InputStream input ;
40
- private OutputStream output ;
41
-
42
- /**
43
- * Needs for NetCatModule
44
- */
45
- @ Inject
46
- public UdpNetCat () {}
19
+ private DatagramSocket socket ;
47
20
48
21
public UdpNetCat ( NetCatListener listener )
49
22
{
50
- this .listener = listener ;
51
- }
52
-
53
- @ Override
54
- public void setListener ( NetCatListener listener )
55
- {
56
- this .listener = listener ;
57
- }
58
-
59
- @ Override
60
- public void setInput ( InputStream input )
61
- {
62
- this .input = input ;
63
- }
64
-
65
- @ Override
66
- public void createOutput ()
67
- {
68
- this .output = new ByteArrayOutputStream ();
69
- }
70
-
71
- @ Override
72
- public void closeOutput ()
73
- {
74
- try {
75
- output .flush ();
76
- output .close ();
77
- } catch ( IOException e ) {
78
- Log .e ( CLASS_NAME , e .getMessage () );
79
- }
80
- output = null ;
81
- }
82
-
83
- @ Override
84
- public OutputStream getOutput ()
85
- {
86
- return output ;
87
- }
88
-
89
- /**
90
- * Strip last CR+LF
91
- */
92
- @ Override
93
- public String getOutputString ()
94
- {
95
- String s = output .toString ();
96
- if ( s .endsWith ( "\n " )) {
97
- s = s .substring ( 0 , s .length () - 1 );
98
- }
99
- return s ;
23
+ super ( listener );
100
24
}
101
25
102
26
@ Override
@@ -121,36 +45,20 @@ public void executeParallel( String... params )
121
45
task .executeOnExecutor ( AsyncTask .THREAD_POOL_EXECUTOR , params );
122
46
}
123
47
124
- /**
125
- * If isListening = true, then isConnected() = true/false
126
- */
127
48
@ Override
128
49
public boolean isListening ()
129
50
{
130
- return serverChannel != null || (( socket instanceof DatagramSocket ) && (( DatagramSocket ) socket ) .isBound () );
51
+ return socket != null && socket .isBound ();
131
52
}
132
53
133
- /**
134
- * If isConnected = true, then isListening() = true
135
- */
136
54
@ Override
137
55
public boolean isConnected ()
138
56
{
139
- if ( socket != null ) {
140
- if ( socket instanceof Socket ) return ( (Socket ) socket ).isConnected ();
141
- if ( socket instanceof DatagramSocket ) return ( (DatagramSocket ) socket ).isConnected ();
142
- }
143
- return false ;
57
+ return socket != null && socket .isConnected ();
144
58
}
145
59
146
- public class NetCatTask extends AsyncTask < String , String , Result >
60
+ public class NetCatTask extends Task
147
61
{
148
- @ Override
149
- protected void onPreExecute ()
150
- {
151
- listener .netCatIsStarted ();
152
- }
153
-
154
62
@ Override
155
63
protected Result doInBackground ( String ... params )
156
64
{
@@ -165,86 +73,46 @@ protected Result doInBackground( String... params )
165
73
String host = params [2 ];
166
74
port = Integer .parseInt ( params [3 ] );
167
75
Log .d ( CLASS_NAME , String .format ( "Connecting to %s:%d (%s)" , host , port , proto ) );
168
- if ( proto == Proto .TCP ) {
169
- socket = new Socket ();
170
- ( (Socket ) socket ).connect ( new InetSocketAddress ( host , port ), 3000 );
171
- } else if ( proto == Proto .UDP ) {
172
- socket = new DatagramSocket ();
173
- ( (DatagramSocket ) socket ).connect ( new InetSocketAddress ( host , port ) );
174
- }
76
+ socket = new DatagramSocket ();
77
+ socket .connect ( new InetSocketAddress ( host , port ) );
175
78
publishProgress ( CONNECTED .toString () );
176
79
result .object = socket ;
177
80
break ;
178
81
case LISTEN :
179
82
proto = Proto .valueOf ( params [1 ] );
180
83
port = Integer .parseInt ( params [2 ] );
181
84
Log .d ( CLASS_NAME , String .format ( "Listening on %d (%s)" , port , proto ) );
182
- if ( proto == Proto .TCP ) {
183
- serverChannel = ServerSocketChannel .open ();
184
- serverChannel .configureBlocking ( false );
185
- serverChannel .socket ().bind ( new InetSocketAddress ( port ) );
186
- publishProgress ( LISTENING .toString () );
187
- while ( !task .isCancelled () ) {
188
- SocketChannel channel = serverChannel .accept ();
189
- Thread .sleep ( 100 );
190
- if ( channel != null ) {
191
- socket = channel .socket ();
192
- result .object = socket ;
193
- publishProgress ( CONNECTED .toString () );
194
- break ;
195
- }
196
- }
197
- if ( task .isCancelled () ) {
198
- stopListening ();
199
- result .exception = new Exception ( "Listening task is cancelled" );
200
- }
201
- } else if ( proto == Proto .UDP ) {
202
- socket = new DatagramSocket ( port );
203
- result .object = socket ;
204
- }
85
+ socket = new DatagramSocket ( port );
86
+ result .object = socket ;
205
87
break ;
206
88
case RECEIVE :
207
- if ( isConnected () && socket instanceof Socket ) {
208
- Log .d ( CLASS_NAME , String .format ( "Receiving from %s" , getSocketRemoteString ( socket )));
209
- receiveFromSocket ( (Socket ) socket );
210
- }
211
- if ( isListening () && socket instanceof DatagramSocket ) {
89
+ if ( isListening () ) {
212
90
// Connect after receive is necessary for further sending
213
- DatagramPacket packet = receiveFromDatagramSocket ( ( DatagramSocket ) socket );
91
+ DatagramPacket packet = receiveFromDatagramSocket ();
214
92
Log .d ( CLASS_NAME , String .format ( "Received data from %s (UDP)" , packet .getSocketAddress () ) );
215
- ( ( DatagramSocket ) socket ) .connect ( packet .getSocketAddress () );
93
+ socket .connect ( packet .getSocketAddress () );
216
94
Log .d ( CLASS_NAME , String .format ( "Connected to %s (UDP)" , packet .getSocketAddress () ) );
217
95
}
218
96
break ;
219
97
case SEND :
220
- if ( isConnected () && socket instanceof Socket ) {
221
- Log .d ( CLASS_NAME , String .format ( "Sending to %s" , getSocketRemoteString ( socket ) ) );
222
- sendToSocket ( (Socket ) socket );
223
- }
224
- if ( isListening () && socket instanceof DatagramSocket ) {
225
- Log .d ( CLASS_NAME , String .format ( "Sending on %d (UDP)" , ( (DatagramSocket ) socket ).getLocalPort () ) );
226
- sendToDatagramSocket ( (DatagramSocket ) socket );
98
+ if ( isConnected () ) {
99
+ Log .d ( CLASS_NAME , String .format ( "Sending to %s (UDP)" , socket .getRemoteSocketAddress () ) );
100
+ sendToDatagramSocket ();
227
101
}
228
102
break ;
229
103
case DISCONNECT :
230
104
if ( isConnected () ) {
231
- Log .d ( CLASS_NAME , String .format ( "Disconnecting from %s" , getSocketRemoteString ( socket )));
232
- if ( socket instanceof Socket ) {
233
- ( (Socket ) socket ).shutdownOutput ();
234
- ( (Socket ) socket ).close ();
235
- } else {
236
- ( (DatagramSocket ) socket ).close ();
237
- }
238
- socket = null ;
239
- publishProgress ( IDLE .toString () );
105
+ Log .d ( CLASS_NAME , String .format ( "Disconnecting from %s (UDP)" , socket .getRemoteSocketAddress () ) );
240
106
}
241
107
if ( isListening () ) {
242
- if ( serverChannel != null ) {
243
- stopListening ();
244
- } else {
245
- stopDatagramListening ();
246
- }
108
+ Log .d ( CLASS_NAME , String .format ( "Stop listening on %d (UDP)" , socket .getLocalPort () ) );
247
109
}
110
+ if ( isConnected () || isListening () ) {
111
+ socket .close ();
112
+ socket = null ;
113
+ publishProgress ( IDLE .toString () );
114
+ }
115
+ break ;
248
116
}
249
117
} catch ( Exception e ) {
250
118
e .printStackTrace ();
@@ -253,60 +121,7 @@ protected Result doInBackground( String... params )
253
121
return result ;
254
122
}
255
123
256
- @ Override
257
- protected void onProgressUpdate ( String ... values )
258
- {
259
- State state = State .valueOf ( String .valueOf ( values [0 ] ) );
260
- EventBus .getDefault ().post ( new ActivityEvent ( state ) );
261
- }
262
-
263
- @ Override
264
- protected void onPostExecute ( Result result )
265
- {
266
- if ( result .exception == null ) {
267
- Log .d ( CLASS_NAME , String .format ( "%s operation is completed" , result .op ) );
268
- listener .netCatIsCompleted ( result );
269
- } else {
270
- Log .e ( CLASS_NAME , result .getErrorMessage () );
271
- listener .netCatIsFailed ( result );
272
- }
273
- }
274
-
275
- @ Override
276
- protected void onCancelled ( Result result )
277
- {
278
- listener .netCatIsFailed ( result );
279
- }
280
-
281
- private void receiveFromSocket ( Socket socket ) throws IOException
282
- {
283
- BufferedReader reader = new BufferedReader ( new InputStreamReader ( socket .getInputStream () ) );
284
- PrintWriter writer = new PrintWriter ( output );
285
- transferStreams ( reader , writer );
286
- }
287
-
288
- private void sendToSocket ( Socket socket ) throws IOException
289
- {
290
- BufferedReader reader = new BufferedReader ( new InputStreamReader ( input ) );
291
- PrintWriter writer = new PrintWriter ( socket .getOutputStream () );
292
- transferStreams ( reader , writer );
293
- }
294
-
295
- private void transferStreams ( BufferedReader reader , PrintWriter writer ) throws IOException
296
- {
297
- try {
298
- String line ;
299
- while ( ( line = reader .readLine () ) != null ) {
300
- writer .println ( line );
301
- writer .flush ();
302
- }
303
- } catch ( AsynchronousCloseException e ) {
304
- // This exception is thrown when socket for receiver thread is closed by netcat
305
- Log .w ( CLASS_NAME , e .toString () );
306
- }
307
- }
308
-
309
- private DatagramPacket receiveFromDatagramSocket ( DatagramSocket socket ) throws IOException
124
+ private DatagramPacket receiveFromDatagramSocket () throws IOException
310
125
{
311
126
byte [] buf = new byte [1024 ];
312
127
DatagramPacket packet = new DatagramPacket ( buf , buf .length );
@@ -315,7 +130,7 @@ private DatagramPacket receiveFromDatagramSocket( DatagramSocket socket ) throws
315
130
return packet ;
316
131
}
317
132
318
- private void sendToDatagramSocket ( DatagramSocket socket ) throws IOException
133
+ private void sendToDatagramSocket () throws IOException
319
134
{
320
135
byte [] buf = new byte [1024 ];
321
136
int bytesRead = input .read ( buf , 0 , buf .length );
@@ -324,35 +139,5 @@ private void sendToDatagramSocket( DatagramSocket socket ) throws IOException
324
139
socket .send ( packet );
325
140
}
326
141
}
327
-
328
- private void stopListening () throws IOException
329
- {
330
- Log .d ( CLASS_NAME , String .format ( "Stop listening on %d (TCP)" , serverChannel .socket ().getLocalPort () ) );
331
- serverChannel .close ();
332
- serverChannel = null ;
333
- }
334
-
335
- private void stopDatagramListening () throws IOException
336
- {
337
- DatagramSocket udpSocket = ( (DatagramSocket ) socket );
338
- Log .d ( CLASS_NAME , String .format ( "Stop listening on %d (UDP)" , udpSocket .getLocalPort () ) );
339
- socket .close ();
340
- socket = null ;
341
- }
342
-
343
- private String getSocketRemoteString ( Closeable socket )
344
- {
345
- if ( socket instanceof Socket ) {
346
- Socket tcpSocket = (Socket ) socket ;
347
- return tcpSocket .getInetAddress ().getHostAddress () + ":" + tcpSocket .getPort ();
348
-
349
- }
350
- if ( socket instanceof DatagramSocket ) {
351
- DatagramSocket udpSocket = (DatagramSocket ) socket ;
352
- return udpSocket .getInetAddress ().getHostAddress () + ":" + udpSocket .getPort ();
353
-
354
- }
355
- return "" ;
356
- }
357
142
}
358
143
}
0 commit comments