-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUdpServer.java
886 lines (716 loc) · 30.8 KB
/
UdpServer.java
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
import java.beans.PropertyChangeEvent;
import java.util.concurrent.ThreadFactory;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.net.MulticastSocket;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Collection;
import java.util.LinkedList;
/**
* <p>A robust class for establishing a UDP server and manipulating
* its listening port and optionally a multicast groups to join.
* The {@link Event}s and property change events make
* it an appropriate tool in a threaded, GUI application.
* It is almost identical in design to the TcpServer class that
* should have accompanied this class when you downloaded it.</p>
*
* <p>To start a UDP server, create a new UdpServer and call start():</p>
*
* <pre> UdpServer server = new UdpServer();
* server.start();</pre>
*
* <p>Of course it won't be much help unless you know which port it's
* listening on and you register as a listener
* so you'll know when a <tt>java.net.DatagramPacket</tt> has come in:</p>
*
* <pre> server.setPort(1234);
* server.addUdpServerListener( new UdpServer.Adapter(){
* public void udpServerPacketReceived( UdpServer.Event evt ){
* DatagramPacket packet = evt.getPacket();
* ...
* } // end packet received
* });</pre>
*
* <p>The server runs on one thread, and all events are fired on that thread.
* If you have to offload heavy processing to another thread, be sure to
* make a copy of the datagram data array since it will be reused the next
* time around. You may use the {@link Event#getPacketAsBytes}
* command as a convenient way to make a copy of the byte array.</p>
*
* <p>The full 64KB allowed by the UDP standard is set aside to receive
* the datagrams, but it's possible that your host platform may truncate that.</p>
*
* <p>The public methods are all synchronized on <tt>this</tt>, and great
* care has been taken to avoid deadlocks and race conditions. That being said,
* there may still be bugs (please contact the author if you find any), and
* you certainly still have the power to introduce these problems yourself.</p>
*
* <p>It's often handy to have your own class extend this one rather than
* making an instance field to hold a UdpServer where you'd have to
* pass along all the setPort(...) methods and so forth.</p>
*
* <p>The supporting {@link Event} and {@link Listener}
* classes are static inner classes in this file so that you have only one
* file to copy to your project. You're welcome.</p>
*
* <p>Since the TcpServer.java, UdpServer.java, and NioServer.java are
* so similar, and since lots of copying and pasting was going on among them,
* you may find some comments that refer to TCP instead of UDP or vice versa.
* Please feel free to let me know, so I can correct that.</p>
*
* <p>This code is released into the Public Domain.
* Since this is Public Domain, you don't need to worry about
* licensing, and you can simply copy this UdpServer.java file
* to your own package and use it as you like. Enjoy.
* Please consider leaving the following statement here in this code:</p>
*
* <p><em>This <tt>UdpServer</tt> class was copied to this project from its source as
* found at <a href="http://iharder.net" target="_blank">iHarder.net</a>.</em></p>
*
* @author Robert Harder
* @author rharder@users.sourceforge.net
* @version 0.1
* @see UdpServer
* @see Event
* @see Listener
*/
public class UdpServer {
private final static Logger LOGGER = Logger.getLogger(UdpServer.class.getName());
/**
* The port property <tt>port</tt> used with
* the property change listeners and the preferences,
* if a preferences object is given.
*/
public final static String PORT_PROP = "port";
private final static int PORT_DEFAULT = 8000;
private int port = PORT_DEFAULT;
/**
* The multicast groups property <tt>groups</tt> used with
* the property change listeners and the preferences,
* if a preferences object is given. If the multicast
* groups is null, then no multicast groups will be joined.
*/
public final static String GROUPS_PROP = "groups";
private final static String GROUPS_DEFAULT = null;
private String groups = GROUPS_DEFAULT;
/**
* <p>One of four possible states for the server to be in:</p>
*
* <ul>
* <li>STARTING</li>
* <li>STARTED</li>
* <li>STOPPING</li>
* <li>STOPPED</li>
* </ul>
*/
public static enum State { STARTING, STARTED, STOPPING, STOPPED };
private State currentState = State.STOPPED;
public final static String STATE_PROP = "state";
private Collection<UdpServer.Listener> listeners = new LinkedList<UdpServer.Listener>(); // Event listeners
private UdpServer.Event event = new UdpServer.Event(this); // Shared event
private PropertyChangeSupport propSupport = new PropertyChangeSupport(this); // Properties
private final UdpServer This = this; // To aid in synchronizing
private ThreadFactory threadFactory; // Optional thread factory
private Thread ioThread; // Performs IO
private MulticastSocket mSocket; // The server
private DatagramPacket packet = new DatagramPacket( new byte[64*1024], 64*1024 ); // Shared datagram
public final static String LAST_EXCEPTION_PROP = "lastException";
private Throwable lastException;
/* ******** C O N S T R U C T O R S ******** */
/**
* Constructs a new UdpServer that will listen on the default port 8000
* (but not until {@link #start} is called).
* The I/O thread will not be in daemon mode.
*/
public UdpServer(){
}
/**
* Constructs a new UdpServer that will listen on the given port
* (but not until {@link #start} is called).
* The I/O thread will not be in daemon mode.
* @param port The initial port on which to listen
*/
public UdpServer( int port ){
this.port = port;
}
/**
* Constructs a new UdpServer that will listen on the given port
* (but not until {@link #start} is called). The provided
* ThreadFactory will be used when starting and running the server.
* @param port The initial port on which to listen
* @param factory The thread factory used to generate a thread to run the server
*/
public UdpServer( int port, ThreadFactory factory ){
this.port = port;
this.threadFactory = factory;
}
/* ******** R U N N I N G ******** */
/**
* Attempts to start the server listening and returns immediately.
* Listen for start events to know if the server was
* successfully started.
*
* @see Listener
*/
public synchronized void start(){
if( this.currentState == UdpServer.State.STOPPED ){ // Only if we're stopped now
assert ioThread == null : ioThread; // Shouldn't have a thread
Runnable run = new Runnable() {
// @Override
public void run() {
runServer(); // This runs for a long time
ioThread = null;
setState( UdpServer.State.STOPPED ); // Clear thread
} // end run
}; // end runnable
if( this.threadFactory != null ){ // User-specified threads
this.ioThread = this.threadFactory.newThread(run);
} else { // Our own threads
this.ioThread = new Thread( run, this.getClass().getName() ); // Named
}
setState( UdpServer.State.STARTING ); // Update state
this.ioThread.start(); // Start thread
} // end if: currently stopped
} // end start
/**
* Attempts to stop the server, if the server is in
* the STARTED state, and returns immediately.
* Be sure to listen for stop events to know if the server was
* successfully stopped.
*
* @see Listener
*/
public synchronized void stop(){
if( this.currentState == UdpServer.State.STARTED ){ // Only if already STARTED
setState( UdpServer.State.STOPPING ); // Mark as STOPPING
if( this.mSocket != null ){
this.mSocket.close();
} // end if: not null
} // end if: already STARTED
} // end stop
/**
* Returns the current state of the server, one of
* STOPPED, STARTING, or STARTED.
* @return state of the server
*/
public synchronized UdpServer.State getState(){
return this.currentState;
}
/**
* Records (sets) the state and fires an event. This method
* does not change what the server is doing, only
* what is reflected by the currentState variable.
* @param state The new state of the server
*/
protected synchronized void setState( UdpServer.State state ){
State oldVal = this.currentState;
this.currentState = state;
firePropertyChange(STATE_PROP,oldVal,state);
}
/**
* Resets the server, if it is running, otherwise does nothing.
* This is accomplished by registering as a listener, stopping
* the server, detecting the stop, unregistering, and starting
* the server again. It's a useful design pattern, and you may
* want to look at the source code for this method to check it out.
*/
public synchronized void reset(){
switch( this.currentState ){
case STARTED:
this.addPropertyChangeListener(STATE_PROP, new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
State newState = (State)evt.getNewValue();
if( newState == State.STOPPED ){
UdpServer server = (UdpServer)evt.getSource();
server.removePropertyChangeListener(STATE_PROP,this);
server.start();
} // end if: stopped
} // end prop change
});
stop();
break;
} // end switch
}
/**
* This method starts up and listens indefinitely
* for UDP packets. On entering this method,
* the state is assumed to be STARTING. Upon exiting
* this method, the state will be STOPPING.
*/
protected void runServer(){
try{
this.mSocket = new MulticastSocket( getPort() ); // Create server
LOGGER.info("UDP Server established on port " + getPort() );
try{
this.mSocket.setReceiveBufferSize( this.packet.getData().length );
LOGGER.info("UDP Server receive buffer size (bytes): " + this.mSocket.getReceiveBufferSize() );
} catch( IOException exc ){
int pl = this.packet.getData().length;
int bl = this.mSocket.getReceiveBufferSize();
LOGGER.warning(String.format( "Could not set receive buffer to %d. It is now at %d. Error: %s",
pl, bl, exc.getMessage() ) );
} // end catch
String gg = getGroups(); // Get multicast groups
if( gg != null ){
String[] proposed = gg.split("[\\s,]+"); // Split along whitespace
for( String p : proposed ){ // See which ones are valid
try{
this.mSocket.joinGroup( InetAddress.getByName(p) );
LOGGER.info( "UDP Server joined multicast group " + p );
} catch( IOException exc ){
LOGGER.warning("Could not join " + p + " as a multicast group: " + exc.getMessage() );
} // end catch
} // end for: each proposed
} // end if: groups not null
setState( State.STARTED ); // Mark as started
LOGGER.info( "UDP Server listening..." );
while( !this.mSocket.isClosed() ){
synchronized( This ){
if( this.currentState == State.STOPPING ){
LOGGER.info( "Stopping UDP Server by request." );
this.mSocket.close();
} // end if: stopping
} // end sync
if( !this.mSocket.isClosed() ){
//////// B L O C K I N G
this.mSocket.receive(packet);
//////// B L O C K I N G
if( LOGGER.isLoggable(Level.FINE) ){
LOGGER.fine( "UDP Server received datagram: " + packet );
}
fireUdpServerPacketReceived();
} //end if: not closed
} // end while: keepGoing
} catch( Exception exc ){
synchronized( This ){
if( this.currentState == State.STOPPING ){ // User asked to stop
this.mSocket.close();
LOGGER.info( "Udp Server closed normally." );
} else {
LOGGER.log( Level.WARNING, "Server closed unexpectedly: " + exc.getMessage(), exc );
} // end else
} // end sync
fireExceptionNotification(exc);
} finally {
setState( State.STOPPING );
if( this.mSocket != null ){
this.mSocket.close();
} // end if: not null
this.mSocket = null;
}
}
/* ******** P A C K E T ******** */
/**
* Returns the last DatagramPacket received.
* @return the shared DatagramPacket
*/
public synchronized DatagramPacket getPacket(){
return this.packet;
}
/**
* Attempts to send a datagram packet on the active
* server socket.
*
* @param packet the packet to send
* @throws java.io.IOException if the server throws an exception
* or if the server is not running (in which case
* there is no underlying server socket to send the datagram)
*/
public synchronized void send( DatagramPacket packet ) throws IOException {
if( this.mSocket == null ){
throw new IOException("No socket available to send packet; is the server running?");
} else {
this.mSocket.send( packet );
}
}
/* ******** R E C E I V E B U F F E R ******** */
/**
* Returns the receive buffer for the underlying MulticastSocket
* if the server is currently running (otherwise there is no
* MulticastSocket to query). Please see the javadocs for
* java.net.MulticastSocket for more information.
*
* @return receive buffer size
* @throws java.net.SocketException
*/
public synchronized int getReceiveBufferSize() throws SocketException{
if( this.mSocket == null ){
throw new SocketException("getReceiveBufferSize() cannot be called when the server is not started.");
} else {
return this.mSocket.getReceiveBufferSize();
}
} // end getReceiveBufferSize
/**
* Recommends a receive buffer size for the underlying MulticastSocket.
* Please see the javadocs for
* java.net.MulticastSocket for more information.
*
* @param size
* @throws java.net.SocketException
*/
public synchronized void setReceiveBufferSize(int size) throws SocketException{
if( this.mSocket == null ){
throw new SocketException("setReceiveBufferSize(..) cannot be called when the server is not started.");
} else {
this.mSocket.setReceiveBufferSize(size);
}
} // end setReceiveBufferSize
/* ******** P O R T ******** */
/**
* Returns the port on which the server is or will be listening.
* @return The port for listening.
*/
public synchronized int getPort(){
return this.port;
}
/**
* Sets the new port on which the server will attempt to listen.
* If the server is already listening, then it will attempt to
* restart on the new port, generating start and stop events.
* @param port the new port for listening
* @throws IllegalArgumentException if port is outside 0..65535
*/
public synchronized void setPort( int port ){
if( port < 0 || port > 65535 ){
throw new IllegalArgumentException( "Cannot set port outside range 0..65535: " + port );
} // end if: port outside range
int oldVal = this.port;
this.port = port;
if( getState() == State.STARTED ){
reset();
} // end if: is running
firePropertyChange( PORT_PROP, oldVal, port );
}
/* ******** M U L T I C A S T G R O U P ******** */
/**
* Returns the multicast groups to which the server has joined.
* May be null.
* @return The multicast groups
*/
public synchronized String getGroups(){
return this.groups;
}
/**
* <p>Sets the new multicast groups to which the server will join.
* If the server is already listening, then it will attempt to
* restart, generating start and stop events. </p>
*
* <p>The list of groups may be whitespace- and/or comma-separated.
* When the server starts up (or restarts), the list will be
* parsed, and only legitimate groups will actually be joined.</p>
* May be null.
*
* @param group the new groups to join
*/
public synchronized void setGroups( String group ){
String oldVal = this.groups;
this.groups = group;
if( getState() == State.STARTED ){
reset();
} // end if: is running
firePropertyChange( GROUPS_PROP, oldVal, this.groups );
}
/* ******** E V E N T S ******** */
/** Adds a {@link Listener}.
* @param l the UdpServer.Listener
*/
public synchronized void addUdpServerListener(UdpServer.Listener l) {
listeners.add(l);
}
/** Removes a {@link Listener}.
* @param l the UdpServer.Listener
*/
public synchronized void removeUdpServerListener(UdpServer.Listener l) {
listeners.remove(l);
}
/**
* Fires event on calling thread for a new packet coming in.
*/
protected synchronized void fireUdpServerPacketReceived() {
UdpServer.Listener[] ll = listeners.toArray(new UdpServer.Listener[ listeners.size() ] );
for( UdpServer.Listener l : ll ){
try{
l.packetReceived(event);
} catch( Exception exc ){
LOGGER.warning("UdpServer.Listener " + l + " threw an exception: " + exc.getMessage() );
fireExceptionNotification(exc);
} // end catch
} // end for: each listener
} // end fireUdpServerPacketReceived
/* ******** P R O P E R T Y C H A N G E ******** */
/**
* Fires property chagne events for all current values
* setting the old value to null and new value to the current.
*/
public synchronized void fireProperties(){
firePropertyChange( PORT_PROP, null, getPort() ); // Port
firePropertyChange( GROUPS_PROP, null, getGroups() ); // Multicast groups
firePropertyChange( STATE_PROP, null, getState() ); // State
}
/**
* Fire a property change event on the current thread.
*
* @param prop name of property
* @param oldVal old value
* @param newVal new value
*/
protected synchronized void firePropertyChange( final String prop, final Object oldVal, final Object newVal ){
try{
propSupport.firePropertyChange(prop,oldVal,newVal);
} catch( Exception exc ){
LOGGER.log(Level.WARNING,
"A property change listener threw an exception: " + exc.getMessage()
,exc);
fireExceptionNotification(exc);
} // end catch
} // end fire
/**
* Add a property listener.
* @param listener the property change listener
*/
public synchronized void addPropertyChangeListener( PropertyChangeListener listener ){
propSupport.addPropertyChangeListener(listener);
}
/**
* Add a property listener for the named property.
* @param property the sole property name for which to register
* @param listener the property change listener
*/
public synchronized void addPropertyChangeListener( String property, PropertyChangeListener listener ){
propSupport.addPropertyChangeListener(property,listener);
}
/**
* Remove a property listener.
* @param listener the property change listener
*/
public synchronized void removePropertyChangeListener( PropertyChangeListener listener ){
propSupport.removePropertyChangeListener(listener);
}
/**
* Remove a property listener for the named property.
* @param property the sole property name for which to stop receiving events
* @param listener the property change listener
*/
public synchronized void removePropertyChangeListener( String property, PropertyChangeListener listener ){
propSupport.removePropertyChangeListener(property,listener);
}
/* ******** E X C E P T I O N S ******** */
/**
* Returns the last exception (Throwable, actually)
* that the server encountered.
* @return last exception
*/
public synchronized Throwable getLastException(){
return this.lastException;
}
/**
* Fires a property change event with the new exception.
* @param t
*/
protected void fireExceptionNotification( Throwable t ){
Throwable oldVal = this.lastException;
this.lastException = t;
firePropertyChange( LAST_EXCEPTION_PROP, oldVal, t );
}
/* ******** L O G G I N G ******** */
/**
* Static method to set the logging level using Java's
* <tt>java.util.logging</tt> package. Example:
* <code>UdpServer.setLoggingLevel(Level.OFF);</code>.
*
* @param level the new logging level
*/
public static void setLoggingLevel( Level level ){
LOGGER.setLevel(level);
}
/**
* Static method returning the logging level using Java's
* <tt>java.util.logging</tt> package.
* @return the logging level
*/
public static Level getLoggingLevel(){
return LOGGER.getLevel();
}
/* ******** ******** */
/* ******** ******** */
/* ******** S T A T I C I N N E R C L A S S L I S T E N E R ******** */
/* ******** ******** */
/* ******** ******** */
/**
* An interface for listening to events from a {@link UdpServer}.
* A single {@link Event} is shared for all invocations
* of these methods.
*
* <p>This code is released into the Public Domain.
* Since this is Public Domain, you don't need to worry about
* licensing, and you can simply copy this UdpServer.java file
* to your own package and use it as you like. Enjoy.
* Please consider leaving the following statement here in this code:</p>
*
* <p><em>This <tt>UdpServer</tt> class was copied to this project from its source as
* found at <a href="http://iharder.net" target="_blank">iHarder.net</a>.</em></p>
*
* @author Robert Harder
* @author rharder@users.sourceforge.net
* @version 0.1
* @see UdpServer
* @see Event
*/
public static interface Listener extends java.util.EventListener {
/**
* Called when a packet is received. This is called on the IO thread,
* so don't take too long, and if you want to offload the processing
* to another thread, be sure to copy the data out of the datagram
* since it will be clobbered the next time around.
*
* @param evt the event
* @see Event#getPacket
*/
public abstract void packetReceived( UdpServer.Event evt );
} // end inner static class Listener
/* ******** ******** */
/* ******** ******** */
/* ******** S T A T I C I N N E R C L A S S A D A P T E R ******** */
/* ******** ******** */
/* ******** ******** */
/**
* A helper class that implements all methods of the
* {@link UdpServer.Listener} interface with empty methods.
*
* <p>This code is released into the Public Domain.
* Since this is Public Domain, you don't need to worry about
* licensing, and you can simply copy this UdpServer.java file
* to your own package and use it as you like. Enjoy.
* Please consider leaving the following statement here in this code:</p>
*
* <p><em>This <tt>UdpServer</tt> class was copied to this project from its source as
* found at <a href="http://iharder.net" target="_blank">iHarder.net</a>.</em></p>
*
* @author Robert Harder
* @author rharder@users.sourceforge.net
* @version 0.1
* @see UdpServer
* @see Listener
* @see Event
*/
// public class Adapter implements UdpServer.Listener {
/**
* Empty call for {@link UdpServer.Listener#udpServerPacketReceived}.
* @param evt the event
*/
// @Override
// public void udpServerPacketReceived( UdpServer.Event evt ) {}
// } // end static inner class Adapter
/* ******** ******** */
/* ******** ******** */
/* ******** S T A T I C I N N E R C L A S S E V E N T ******** */
/* ******** ******** */
/* ******** ******** */
/**
* An event representing activity by a {@link UdpServer}.
*
* <p>This code is released into the Public Domain.
* Since this is Public Domain, you don't need to worry about
* licensing, and you can simply copy this UdpServer.java file
* to your own package and use it as you like. Enjoy.
* Please consider leaving the following statement here in this code:</p>
*
* <p><em>This <tt>UdpServer</tt> class was copied to this project from its source as
* found at <a href="http://iharder.net" target="_blank">iHarder.net</a>.</em></p>
*
* @author Robert Harder
* @author rharder@users.sourceforge.net
* @version 0.1
* @see UdpServer
* @see Listener
*/
public static class Event extends java.util.EventObject {
private final static long serialVersionUID = 1;
/**
* Creates a Event based on the given {@link UdpServer}.
* @param src the source of the event
*/
public Event( UdpServer src ){
super(src);
}
/**
* Returns the source of the event, a {@link UdpServer}.
* Shorthand for <tt>(UdpServer)getSource()</tt>.
* @return the server
*/
public UdpServer getUdpServer(){
return (UdpServer)getSource();
}
/**
* Shorthand for <tt>getUdpServer().getState()</tt>.
* @return the state of the server
* @see UdpServer.State
*/
public UdpServer.State getState(){
return getUdpServer().getState();
}
/**
* Returns the most recent datagram packet received
* by the {@link UdpServer}. Shorthand for
* <tt>getUdpServer().getPacket()</tt>.
* @return the most recent datagram
*/
public DatagramPacket getPacket(){
return getUdpServer().getPacket();
}
/**
* Copies and returns the bytes in the most recently
* received packet, or null if not available.
* @return a copy of the datagram's byte array
*/
public byte[] getPacketAsBytes(){
DatagramPacket packet = getPacket();
if( packet == null ){
return null;
} else {
byte[] data = new byte[ packet.getLength() ];
System.arraycopy(
packet.getData(), packet.getOffset(),
data, 0, data.length );
return data;
} // end else
} // end getPacketAsBytes
/**
* Returns the data in the most recently-received
* packet as if it were a String
* or null if not available.
* @return The datagram as a string
*/
public String getPacketAsString(){
DatagramPacket packet = getPacket();
if( packet == null ){
return null;
} else {
String s = new String(
packet.getData(),
packet.getOffset(),
packet.getLength() );
return s;
} // end else
}
/**
* Convenience method for sending datagram packets,
* intended to be used for replying to the sender but
* could be used for anything. Equivalent to
* <code>evt.getUdpServer.send( packet )</code>.
*
* @param packet the packet to send
* @throws java.io.IOException if the server throws an exception
* or if the server is not running (in which case
* there is no underlying server socket to send the datagram)
*/
public void send( DatagramPacket packet ) throws IOException {
this.getUdpServer().send( packet );
}
} // end static inner class Event
} // end class UdpServer