summaryrefslogtreecommitdiffstats
path: root/libraries/oscP5/src/netP5/AbstractTcpClient.java
blob: 7f6cac4602d55991b55ab6e9f9834bb767df85a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/**
 * A network library for processing which supports UDP, TCP and Multicast.
 *
 * (c) 2004-2012
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 * 
 * @author		Andreas Schlegel http://www.sojamo.de
 * @modified	12/23/2012
 * @version		0.9.9
 */

package netP5;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;


/**
 * @invisible
 */
public abstract class AbstractTcpClient implements Runnable {

  private Socket _mySocket;

  protected TcpPacketListener _myTcpPacketListener;

  private PrintWriter _myOutput = null;

  private BufferedReader _myInput = null;

  private OutputStream _myOutputStream = null;

  protected byte[] _myBytes = new byte[0];

  protected StringBuffer _myStringBuffer = new StringBuffer(0);

  protected AbstractTcpServer _myTcpServer;

  protected NetAddress _myNetAddress;

  protected int _myServerPort;

  private Thread _myThread;

  private char TERMINATOR = '\0';
  
  /**
   * terminator is readline.
   */
  public static final int MODE_READLINE = 0;

  /**
   * terminator is terminated, by default this is character '\0'
   * and can be set with setTerminator
   */
  public static final int MODE_TERMINATED = 1;

  /**
   * terminator is newline.
   */
  public static final int MODE_NEWLINE = 2;
  
  /**
   * no terminator required, packets are sent via
   * a tcp stream.
   */
  public static final int MODE_STREAM = 3;

  private final int _myMode;

  /**
   * @invisible
   * @param theTcpPacketListener TcpPacketListener
   * @param theHost String
   * @param thePort int
   */
  public AbstractTcpClient(final TcpPacketListener theTcpPacketListener,
                           final String theHost,
                           final int thePort) {
    this(theTcpPacketListener, theHost, thePort, MODE_READLINE);
  }

  /**
   * @invisible
   * @param theHost String
   * @param thePort int
   */
  public AbstractTcpClient(final String theHost,
                           final int thePort) {
    this(null, theHost, thePort, MODE_READLINE);
  }

  /**
   * @invisible
   * @param theTcpPacketListener TcpPacketListener
   * @param theHost String
   * @param thePort int
   * @param theMode int
   */
  public AbstractTcpClient(final TcpPacketListener theTcpPacketListener,
                           final String theHost,
                           final int thePort,
                           final int theMode) {
    _myTcpPacketListener = theTcpPacketListener;
    _myNetAddress = new NetAddress(theHost, thePort);
    _myMode = theMode;
    startSocket();
  }

  /**
   * @invisible
   * @param theHost String
   * @param thePort int
   * @param theMode int
   */
  public AbstractTcpClient(final String theHost,
                           final int thePort,
                           final int theMode) {
    this(null, theHost, thePort, theMode);
  }


  /**
   * @invisible
   * @param theTcpServer AbstractTcpServer
   * @param theSocket Socket
   * @param theTcpPacketListener TcpPacketListener
   * @param theServerPort int
   * @param theMode int
   */
  public AbstractTcpClient(final AbstractTcpServer theTcpServer,
                           final Socket theSocket,
                           final TcpPacketListener theTcpPacketListener,
                           final int theServerPort,
                           final int theMode) {
    _myTcpServer = theTcpServer;
    _mySocket = theSocket;
    _myTcpPacketListener = theTcpPacketListener;
    _myServerPort = theServerPort;
    _myMode = theMode;
    startSocket();
  }


  private void startSocket() {
    try {
      if (_mySocket == null) {
        _mySocket = new Socket(_myNetAddress.address(), _myNetAddress.port());
      } else {
        _myNetAddress = new NetAddress(_mySocket.getInetAddress().getHostAddress(),
                                       _mySocket.getPort());
      }
      Logger.printProcess("TcpClient", "### starting new TcpClient " + _myNetAddress);
      if (_myMode == MODE_STREAM) {
        _myOutputStream = _mySocket.getOutputStream();
      }
      init();
    } catch (final IOException e) {
      Logger.printError("TcpClient",
                        "IOException while trying to create a new socket.");
//      handleStatus(NetStatus.CONNECTION_FAILED); // FIX! NetPlug is still null at this point.  NetPlug has to exist first.
    }
  }


  /**
   * when a TCP connection is lost, reconnect to the server with reconnect().
   */
  public void reconnect() {
    try {
      Thread.sleep(1000);
    } catch(final Exception e) { }
    startSocket();
  }


  private void init() {
    _myThread = new Thread(this);
    _myThread.start();
  }

  /**
   * to parse an incomming tcp message, a terminator character is required to
   * determine the end of the message so that it can be parsed and forwarded.
   *  
   * @param theTerminator
   */
  public void setTerminator(final char theTerminator) {
    TERMINATOR = theTerminator;
  }

  /**
   * stop and dispose a tcp client.
   */
  public void dispose() {
    try {
      // do io streams need to be closed first?
      if (_myInput != null) {
        _myInput.close();
      }
      if (_myOutput != null) {
        _myOutput.close();
      }

    } catch (final Exception e) {
      e.printStackTrace();
    }
    _myInput = null;
    _myOutput = null;

    try {
      if (_mySocket != null) {
        _mySocket.close();
      }

    } catch (final Exception e) {
      e.printStackTrace();
    }
    if(_myThread==null) {
      return;
    }
    _mySocket = null;
    _myThread = null;
    handleStatus(NetStatus.CONNECTION_CLOSED);
    Logger.printProcess("TcpClient.dispose", "TcpClient closed.");
  }

  /**
   * @invisible
   */
  public void run() {
    if (_myMode == MODE_STREAM) {
      try {
        try {
          // sleep a little bit to avoid threading and nullpointer
          // issues when reconnecting.
          _myThread.sleep(500);
        } catch (final Exception e) {

        }

        final InputStream in = _mySocket.getInputStream();
        while (!_mySocket.isClosed() && _mySocket != null) {
          final int myLen = Bytes.toIntBigEndian(in);
          if (myLen < 0) {
            break;
          }
          _myBytes = Bytes.toByteArray(in, myLen);
          handleInput();
        }
      } catch (final java.net.SocketException se) {
        System.out.println("Connection reset.");
      } catch (final Exception e) {
        System.out.println("### EXCEPTION " + e);
      }
      try {
        handleStatus(NetStatus.SERVER_CLOSED);
        handleStatus(NetStatus.CONNECTION_TERMINATED);
        dispose();
      } catch (final NullPointerException e) {
        System.out.println("### nullpointer while calling handleStatus.");
      }
    } else {
      while (Thread.currentThread() == _myThread) {
        switch (_myMode) {
        case (MODE_TERMINATED):
          read();
          break;
        case (MODE_READLINE):
        default:
          readline();
          break;
        }
        break;
      }
    }
    if (_myTcpServer != null) {
      _mySocket = null;
      _myTcpServer.remove(this);
    }
  }


  private void read() {
    try {
      _myInput = new BufferedReader(new InputStreamReader(_mySocket.getInputStream()));

      final char[] charBuffer = new char[1];
      while (_myInput.read(charBuffer, 0, 1) != -1) {

        /**@todo
         * StringBuffer size is limited yet.
         * increase the buffer size dynamically.
         */
        _myStringBuffer = new StringBuffer(4096);
        while (charBuffer[0] != TERMINATOR && charBuffer[0] != 3) {
          _myStringBuffer.append(charBuffer[0]);
          _myInput.read(charBuffer, 0, 1);
        }
        _myBytes = _myStringBuffer.toString().getBytes();
        handleInput();
      }
    } catch (final IOException e) {
      Logger.printProcess("TcpClient.read()", "connection has been terminated.");
      if (_myTcpServer == null) {
        handleStatus(NetStatus.SERVER_CLOSED);
      }
      handleStatus(NetStatus.CONNECTION_TERMINATED);
    }
  }


  private void readline() {
    try {
      _myOutput = new PrintWriter(_mySocket.getOutputStream(), true);
      _myInput = new BufferedReader(new InputStreamReader(_mySocket.getInputStream()));
      String inputLine;

      while ((inputLine = _myInput.readLine()) != null) {
        _myStringBuffer = new StringBuffer(inputLine);
        _myBytes = _myStringBuffer.toString().getBytes();
        handleInput();
      }
    } catch (final IOException e) {
      Logger.printProcess("TcpClient.readline()", "connection has been terminated.");
      handleStatus(NetStatus.CONNECTION_TERMINATED);
      if (_myTcpServer == null) {
        handleStatus(NetStatus.SERVER_CLOSED);
      }
    }
  }

  /**
   * @invisible
   */
  public abstract void handleInput();

  /**
   * @invisible
   * @param theIndex
   */
  public abstract void handleStatus(int theIndex);

  /**
   * @invisible
   * @return
   */
  public TcpPacketListener listener() {
    return _myTcpPacketListener;
  }

  /**
   * get the server port.
   * @return
   */
  public int serverport() {
    return _myServerPort;
  }

  /**
   * get the instance of the socket. more info at java.net.Socket
   * @return
   */
  public Socket socket() {
    return _mySocket;
  }

  
  /**
   * get the mode of the terminator. 
   * @return
   */
  public int mode() {
    return _myMode;
  }


  public String getString() {
    return _myStringBuffer.toString();
  }


  public StringBuffer getStringBuffer() {
    return _myStringBuffer;
  }


  public void send(final byte[] theBytes) {
    if (_myMode == MODE_STREAM) {
      try {
        Bytes.toStream(_myOutputStream, theBytes);
      } catch (final Exception ex) {
        handleStatus(NetStatus.SEND_FAILED);
      }
    } else {
      System.out.println("### sending bytes is only supported for STREAMs");
    }
  }


  public void send(final byte[][] theBytes) {
    if (_myMode == MODE_STREAM) {
      try {
        for (int i = 0; i < theBytes.length; i++) {
          Bytes.toStream(_myOutputStream, theBytes[i]);
        }
      } catch (final Exception ex) {
        handleStatus(NetStatus.SEND_FAILED);
      }
    } else {
      System.out.println("### sending bytes is only supported for STREAMs");
    }

  }


  public void send(final String theString) {
    if (_myMode == MODE_STREAM) {
      send(theString.getBytes());
    } else {
      switch (_myMode) {
      case (MODE_TERMINATED):
        _myOutput.write(theString + TERMINATOR);
        break;
      case (MODE_NEWLINE):
        _myOutput.write(theString + "\n");
        break;
      case (MODE_READLINE):
      default:
        _myOutput.println(theString);
        break;
      }
      _myOutput.flush();
    }
  }


  public NetAddress netAddress() {
    return _myNetAddress;
  }


  /**
   * @deprecated
   * @invisible
   * @return NetAddress
   */

  public NetAddress netaddress() {
    return _myNetAddress;
  }


  /**
   * @param theNetAddress NetAddress
   * @return boolean
   */
  public boolean equals(final NetAddress theNetAddress) {
    if (theNetAddress.address().equals(_myNetAddress.address()) &&
        theNetAddress.port() == _myNetAddress.port()) {
      return true;
    }
    return false;
  }


  public boolean equals(final TcpClient theClient) {
    return equals(theClient.netAddress());
  }

}