Class UdpServer

java.lang.Object
  extended by UdpServer

public class UdpServer
extends java.lang.Object

A robust class for establishing a UDP server and manipulating its listening port and optionally a multicast groups to join. The UdpServer.Events 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.

To start a UDP server, create a new UdpServer and call start():

 UdpServer server = new UdpServer();
 server.start();

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 java.net.DatagramPacket has come in:

 server.setPort(1234);
  server.addUdpServerListener( new UdpServer.Adapter(){
     public void udpServerPacketReceived( UdpServer.Event evt ){
         DatagramPacket packet = evt.getPacket();
         ...
     }   // end packet received
 });

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 UdpServer.Event.getPacketAsBytes() command as a convenient way to make a copy of the byte array.

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.

The public methods are all synchronized on this, 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.

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.

The supporting UdpServer.Event and UdpServer.Listener classes are static inner classes in this file so that you have only one file to copy to your project. You're welcome.

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.

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:

This UdpServer class was copied to this project from its source as found at iHarder.net.

Author:
Robert Harder, rharder@users.sourceforge.net
See Also:
UdpServer, UdpServer.Event, UdpServer.Listener

Nested Class Summary
static class UdpServer.Event
          An event representing activity by a UdpServer.
static interface UdpServer.Listener
          An interface for listening to events from a UdpServer.
static class UdpServer.State
          One of four possible states for the server to be in:
 
Field Summary
static java.lang.String GROUPS_PROP
          The multicast groups property groups used with the property change listeners and the preferences, if a preferences object is given.
static java.lang.String LAST_EXCEPTION_PROP
           
static java.lang.String PORT_PROP
          The port property port used with the property change listeners and the preferences, if a preferences object is given.
static java.lang.String STATE_PROP
           
 
Constructor Summary
UdpServer()
          Constructs a new UdpServer that will listen on the default port 8000 (but not until start() is called).
UdpServer(int port)
          Constructs a new UdpServer that will listen on the given port (but not until start() is called).
UdpServer(int port, java.util.concurrent.ThreadFactory factory)
          Constructs a new UdpServer that will listen on the given port (but not until start() is called).
 
Method Summary
 void addPropertyChangeListener(java.beans.PropertyChangeListener listener)
          Add a property listener.
 void addPropertyChangeListener(java.lang.String property, java.beans.PropertyChangeListener listener)
          Add a property listener for the named property.
 void addUdpServerListener(UdpServer.Listener l)
          Adds a UdpServer.Listener.
protected  void fireExceptionNotification(java.lang.Throwable t)
          Fires a property change event with the new exception.
 void fireProperties()
          Fires property chagne events for all current values setting the old value to null and new value to the current.
protected  void firePropertyChange(java.lang.String prop, java.lang.Object oldVal, java.lang.Object newVal)
          Fire a property change event on the current thread.
protected  void fireUdpServerPacketReceived()
          Fires event on calling thread for a new packet coming in.
 java.lang.String getGroups()
          Returns the multicast groups to which the server has joined.
 java.lang.Throwable getLastException()
          Returns the last exception (Throwable, actually) that the server encountered.
static java.util.logging.Level getLoggingLevel()
          Static method returning the logging level using Java's java.util.logging package.
 java.net.DatagramPacket getPacket()
          Returns the last DatagramPacket received.
 int getPort()
          Returns the port on which the server is or will be listening.
 int getReceiveBufferSize()
          Returns the receive buffer for the underlying MulticastSocket if the server is currently running (otherwise there is no MulticastSocket to query).
 UdpServer.State getState()
          Returns the current state of the server, one of STOPPED, STARTING, or STARTED.
 void removePropertyChangeListener(java.beans.PropertyChangeListener listener)
          Remove a property listener.
 void removePropertyChangeListener(java.lang.String property, java.beans.PropertyChangeListener listener)
          Remove a property listener for the named property.
 void removeUdpServerListener(UdpServer.Listener l)
          Removes a UdpServer.Listener.
 void reset()
          Resets the server, if it is running, otherwise does nothing.
protected  void runServer()
          This method starts up and listens indefinitely for UDP packets.
 void send(java.net.DatagramPacket packet)
          Attempts to send a datagram packet on the active server socket.
 void setGroups(java.lang.String group)
          Sets the new multicast groups to which the server will join.
static void setLoggingLevel(java.util.logging.Level level)
          Static method to set the logging level using Java's java.util.logging package.
 void setPort(int port)
          Sets the new port on which the server will attempt to listen.
 void setReceiveBufferSize(int size)
          Recommends a receive buffer size for the underlying MulticastSocket.
protected  void setState(UdpServer.State state)
          Records (sets) the state and fires an event.
 void start()
          Attempts to start the server listening and returns immediately.
 void stop()
          Attempts to stop the server, if the server is in the STARTED state, and returns immediately.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

PORT_PROP

public static final java.lang.String PORT_PROP
The port property port used with the property change listeners and the preferences, if a preferences object is given.

See Also:
Constant Field Values

GROUPS_PROP

public static final java.lang.String GROUPS_PROP
The multicast groups property groups 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.

See Also:
Constant Field Values

STATE_PROP

public static final java.lang.String STATE_PROP
See Also:
Constant Field Values

LAST_EXCEPTION_PROP

public static final java.lang.String LAST_EXCEPTION_PROP
See Also:
Constant Field Values
Constructor Detail

UdpServer

public UdpServer()
Constructs a new UdpServer that will listen on the default port 8000 (but not until start() is called). The I/O thread will not be in daemon mode.


UdpServer

public UdpServer(int port)
Constructs a new UdpServer that will listen on the given port (but not until start() is called). The I/O thread will not be in daemon mode.

Parameters:
port - The initial port on which to listen

UdpServer

public UdpServer(int port,
                 java.util.concurrent.ThreadFactory factory)
Constructs a new UdpServer that will listen on the given port (but not until start() is called). The provided ThreadFactory will be used when starting and running the server.

Parameters:
port - The initial port on which to listen
factory - The thread factory used to generate a thread to run the server
Method Detail

start

public void start()
Attempts to start the server listening and returns immediately. Listen for start events to know if the server was successfully started.

See Also:
UdpServer.Listener

stop

public void stop()
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 Also:
UdpServer.Listener

getState

public UdpServer.State getState()
Returns the current state of the server, one of STOPPED, STARTING, or STARTED.

Returns:
state of the server

setState

protected void setState(UdpServer.State state)
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.

Parameters:
state - The new state of the server

reset

public void reset()
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.


runServer

protected void runServer()
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.


getPacket

public java.net.DatagramPacket getPacket()
Returns the last DatagramPacket received.

Returns:
the shared DatagramPacket

send

public void send(java.net.DatagramPacket packet)
          throws java.io.IOException
Attempts to send a datagram packet on the active server socket.

Parameters:
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)

getReceiveBufferSize

public int getReceiveBufferSize()
                         throws java.net.SocketException
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.

Returns:
receive buffer size
Throws:
java.net.SocketException

setReceiveBufferSize

public void setReceiveBufferSize(int size)
                          throws java.net.SocketException
Recommends a receive buffer size for the underlying MulticastSocket. Please see the javadocs for java.net.MulticastSocket for more information.

Parameters:
size -
Throws:
java.net.SocketException

getPort

public int getPort()
Returns the port on which the server is or will be listening.

Returns:
The port for listening.

setPort

public void setPort(int 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.

Parameters:
port - the new port for listening
Throws:
java.lang.IllegalArgumentException - if port is outside 0..65535

getGroups

public java.lang.String getGroups()
Returns the multicast groups to which the server has joined. May be null.

Returns:
The multicast groups

setGroups

public void setGroups(java.lang.String group)

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.

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.

May be null.

Parameters:
group - the new groups to join

addUdpServerListener

public void addUdpServerListener(UdpServer.Listener l)
Adds a UdpServer.Listener.

Parameters:
l - the UdpServer.Listener

removeUdpServerListener

public void removeUdpServerListener(UdpServer.Listener l)
Removes a UdpServer.Listener.

Parameters:
l - the UdpServer.Listener

fireUdpServerPacketReceived

protected void fireUdpServerPacketReceived()
Fires event on calling thread for a new packet coming in.


fireProperties

public void fireProperties()
Fires property chagne events for all current values setting the old value to null and new value to the current.


firePropertyChange

protected void firePropertyChange(java.lang.String prop,
                                  java.lang.Object oldVal,
                                  java.lang.Object newVal)
Fire a property change event on the current thread.

Parameters:
prop - name of property
oldVal - old value
newVal - new value

addPropertyChangeListener

public void addPropertyChangeListener(java.beans.PropertyChangeListener listener)
Add a property listener.

Parameters:
listener - the property change listener

addPropertyChangeListener

public void addPropertyChangeListener(java.lang.String property,
                                      java.beans.PropertyChangeListener listener)
Add a property listener for the named property.

Parameters:
property - the sole property name for which to register
listener - the property change listener

removePropertyChangeListener

public void removePropertyChangeListener(java.beans.PropertyChangeListener listener)
Remove a property listener.

Parameters:
listener - the property change listener

removePropertyChangeListener

public void removePropertyChangeListener(java.lang.String property,
                                         java.beans.PropertyChangeListener listener)
Remove a property listener for the named property.

Parameters:
property - the sole property name for which to stop receiving events
listener - the property change listener

getLastException

public java.lang.Throwable getLastException()
Returns the last exception (Throwable, actually) that the server encountered.

Returns:
last exception

fireExceptionNotification

protected void fireExceptionNotification(java.lang.Throwable t)
Fires a property change event with the new exception.

Parameters:
t -

setLoggingLevel

public static void setLoggingLevel(java.util.logging.Level level)
Static method to set the logging level using Java's java.util.logging package. Example: UdpServer.setLoggingLevel(Level.OFF);.

Parameters:
level - the new logging level

getLoggingLevel

public static java.util.logging.Level getLoggingLevel()
Static method returning the logging level using Java's java.util.logging package.

Returns:
the logging level