diff --git a/src/main/java/org/ice4j/socket/GoogleRelayedCandidateDelegate.java b/src/main/java/org/ice4j/socket/GoogleRelayedCandidateDelegate.java
index b0e2cb5..4a1ccd7 100644
--- a/src/main/java/org/ice4j/socket/GoogleRelayedCandidateDelegate.java
+++ b/src/main/java/org/ice4j/socket/GoogleRelayedCandidateDelegate.java
@@ -343,7 +343,7 @@ public class GoogleRelayedCandidateDelegate
{
DatagramPacket packetToReceive = packetsToReceive.remove(0);
- MultiplexingDatagramSocket.copy(packetToReceive, p);
+ MultiplexingXXXSocketSupport.copy(packetToReceive, p);
packetsToReceive.notifyAll();
break;
}
@@ -372,7 +372,7 @@ public class GoogleRelayedCandidateDelegate
}
else
{
- packetsToSend.add(MultiplexingDatagramSocket.clone(p));
+ packetsToSend.add(MultiplexingXXXSocketSupport.clone(p));
if (sendThread == null)
createSendThread();
else
diff --git a/src/main/java/org/ice4j/socket/MultiplexedDatagramSocket.java b/src/main/java/org/ice4j/socket/MultiplexedDatagramSocket.java
index e6b2609..595830d 100644
--- a/src/main/java/org/ice4j/socket/MultiplexedDatagramSocket.java
+++ b/src/main/java/org/ice4j/socket/MultiplexedDatagramSocket.java
@@ -35,6 +35,7 @@ import java.util.*;
*/
public class MultiplexedDatagramSocket
extends DelegatingDatagramSocket
+ implements MultiplexedXXXSocket
{
/**
* The DatagramPacketFilter which determines which
@@ -120,14 +121,9 @@ public class MultiplexedDatagramSocket
}
/**
- * Gets the DatagramPacketFilter which determines which
- * DatagramPackets read from the network are to be received through
- * this DatagramSocket.
- *
- * @return the DatagramPacketFilter which determines which
- * DatagramPackets read from the network are to be received through
- * this DatagramSocket
+ * {@inheritDoc}
*/
+ @Override
public DatagramPacketFilter getFilter()
{
return filter;
diff --git a/src/main/java/org/ice4j/socket/MultiplexedSocket.java b/src/main/java/org/ice4j/socket/MultiplexedSocket.java
index a68d642..21c27d6 100644
--- a/src/main/java/org/ice4j/socket/MultiplexedSocket.java
+++ b/src/main/java/org/ice4j/socket/MultiplexedSocket.java
@@ -35,6 +35,7 @@ import java.util.logging.*;
*/
public class MultiplexedSocket
extends DelegatingSocket
+ implements MultiplexedXXXSocket
{
/**
* The Logger used by the MultiplexedSocket class and its
@@ -130,14 +131,9 @@ public class MultiplexedSocket
}
/**
- * Gets the DatagramPacketFilter which determines which
- * DatagramPackets read from the network are to be received through
- * this Socket.
- *
- * @return the DatagramPacketFilter which determines which
- * DatagramPackets read from the network are to be received through
- * this Socket
+ * {@inheritDoc}
*/
+ @Override
public DatagramPacketFilter getFilter()
{
return filter;
diff --git a/src/main/java/org/ice4j/socket/MultiplexedXXXSocket.java b/src/main/java/org/ice4j/socket/MultiplexedXXXSocket.java
new file mode 100644
index 0000000..8f8e03a
--- /dev/null
+++ b/src/main/java/org/ice4j/socket/MultiplexedXXXSocket.java
@@ -0,0 +1,39 @@
+/*
+ * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
+ *
+ * Copyright @ 2015 Atlassian Pty Ltd
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.ice4j.socket;
+
+/**
+ * Defines the application programming interface (API) expected of pseudo
+ * sockets which are in fact {@code DatagramPacket}-based views of actual
+ * sockets.
+ *
+ * @author Lyubomir Marinov
+ */
+interface MultiplexedXXXSocket
+{
+ /**
+ * Gets the {@code DatagramPacketFilter} which determines which
+ * {@code DatagramPacket}s read from the network are to be received through
+ * this socket.
+ *
+ * @return the {@code DatagramPacketFilter} which determines which
+ * {@code DatagramPacket}s read from the network are to be received through
+ * this socket
+ */
+ DatagramPacketFilter getFilter();
+}
diff --git a/src/main/java/org/ice4j/socket/MultiplexingDatagramSocket.java b/src/main/java/org/ice4j/socket/MultiplexingDatagramSocket.java
index c491719..a802584 100644
--- a/src/main/java/org/ice4j/socket/MultiplexingDatagramSocket.java
+++ b/src/main/java/org/ice4j/socket/MultiplexingDatagramSocket.java
@@ -18,10 +18,8 @@
package org.ice4j.socket;
import java.io.*;
-import java.lang.reflect.*;
import java.net.*;
import java.util.*;
-import java.util.logging.*;
/**
* Represents a DatagramSocket which allows filtering
@@ -36,199 +34,69 @@ public class MultiplexingDatagramSocket
extends SafeCloseDatagramSocket
{
/**
- * The Logger used by the MultiplexingDatagramSocket class
- * and its instances for logging output.
+ * The {@code MultiplexingXXXSocketSupport} which implements functionality
+ * common to TCP and UDP sockets in order to facilitate implementers such as
+ * this instance.
*/
- private static final Logger logger
- = Logger.getLogger(MultiplexingDatagramSocket.class.getName());
-
- /**
- * The constant which represents an empty array with
- * MultiplexedDatagramSocket element type. Explicitly defined in
- * order to reduce allocations.
- */
- private static final MultiplexedDatagramSocket[] NO_SOCKETS
- = new MultiplexedDatagramSocket[0];
-
- static T[] add(T[] array, T element)
- {
- int length = array.length;
- @SuppressWarnings("unchecked")
- T[] newArray
- = (T[])
- Array.newInstance(
- array.getClass().getComponentType(),
- length + 1);
-
- if (length != 0)
- {
- System.arraycopy(array, 0, newArray, 0, length);
- }
- newArray[length] = element;
- return newArray;
- }
-
- /**
- * Initializes a new DatagramPacket instance which is a clone of a
- * specific DatagramPacket i.e. the properties of the clone
- * DatagramPacket are clones of the specified
- * DatagramPacket.
- *
- * @param p the DatagramPacket to clone
- * @return a new DatagramPacket instance which is a clone of the
- * specified DatagramPacket
- */
- public static DatagramPacket clone(DatagramPacket p)
- {
- return clone(p, /* arraycopy */ true);
- }
-
- /**
- * Initializes a new DatagramPacket instance which is a clone of a
- * specific DatagramPacket i.e. the properties of the clone
- * DatagramPacket are clones of the specified
- * DatagramPacket.
- *
- * @param p the DatagramPacket to clone
- * @param arraycopy true if the actual bytes of the data of
- * p are to be copied into the clone or false if only the
- * capacity of the data of p is to be cloned without copying the
- * actual bytes of the data of p
- * @return a new DatagramPacket instance which is a clone of the
- * specified DatagramPacket
- */
- public static DatagramPacket clone(DatagramPacket p, boolean arraycopy)
- {
- byte[] data;
- int off;
- int len;
- InetAddress address;
- int port;
-
- synchronized (p)
- {
- data = p.getData();
- off = p.getOffset();
- len = p.getLength();
-
- // Clone the data.
+ private final MultiplexingXXXSocketSupport
+ multiplexingXXXSocketSupport
+ = new MultiplexingXXXSocketSupport(
+ MultiplexedDatagramSocket.class)
{
- // The capacity of the specified p is preserved.
- byte[] dataClone = new byte[data.length];
-
- // However, only copy the range of data starting with off and
- // spanning len number of bytes. Of course, preserve off and len
- // in addition to the capacity.
- if (arraycopy && (len > 0))
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected MultiplexedDatagramSocket createSocket(
+ DatagramPacketFilter filter)
+ throws SocketException
{
- int arraycopyOff, arraycopyLen;
-
- // If off and/or len are going to cause an exception though,
- // copy the whole data.
- if ((off >= 0)
- && (off < data.length)
- && (off + len <= data.length))
- {
- arraycopyOff = off;
- arraycopyLen = len;
- }
- else
- {
- arraycopyOff = 0;
- arraycopyLen = data.length;
- }
- System.arraycopy(
- data, arraycopyOff,
- dataClone, arraycopyOff,
- arraycopyLen);
+ return
+ new MultiplexedDatagramSocket(
+ MultiplexingDatagramSocket.this,
+ filter);
}
- data = dataClone;
- }
- address = p.getAddress();
- port = p.getPort();
- }
-
- DatagramPacket c = new DatagramPacket(data, off, len);
-
- if (address != null)
- c.setAddress(address);
- if (port >= 0)
- c.setPort(port);
-
- return c;
- }
-
- /**
- * Copies the properties of a specific DatagramPacket to another
- * DatagramPacket. The property values are not cloned.
- *
- * @param src the DatagramPacket which is to have its properties
- * copied to dest
- * @param dest the DatagramPacket which is to have its properties
- * set to the value of the respective properties of src
- */
- public static void copy(DatagramPacket src, DatagramPacket dest)
- {
- synchronized (dest)
- {
- dest.setAddress(src.getAddress());
- dest.setPort(src.getPort());
-
- byte[] srcData = src.getData();
-
- if (srcData == null)
- {
- dest.setLength(0);
- }
- else
- {
- byte[] destData = dest.getData();
-
- if (destData == null)
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected void doReceive(DatagramPacket p)
+ throws IOException
{
- dest.setLength(0);
+ multiplexingXXXSocketSupportDoReceive(p);
}
- else
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected void doSetReceiveBufferSize(int receiveBufferSize)
+ throws SocketException
{
- int destOffset = dest.getOffset();
- int destLength = destData.length - destOffset;
- int srcLength = src.getLength();
-
- if (destLength >= srcLength)
- {
- destLength = srcLength;
- }
- else if (logger.isLoggable(Level.WARNING))
- {
- logger.log(
- Level.WARNING,
- "Truncating received DatagramPacket data!");
- }
- System.arraycopy(
- srcData, src.getOffset(),
- destData, destOffset,
- destLength);
- dest.setLength(destLength);
+ multiplexingXXXSocketSupportDoSetReceiveBufferSize(
+ receiveBufferSize);
}
- }
- }
- }
- /**
- * The indicator which determines whether this DatagramSocket is
- * currently reading from the network using
- * {@link DatagramSocket#receive(DatagramPacket)}. When true,
- * subsequent requests to read from the network will be blocked until the
- * current read is finished.
- */
- private boolean inReceive = false;
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected List getReceived()
+ {
+ return received;
+ }
- /**
- * The value with which {@link DatagramSocket#setReceiveBufferSize(int)} is
- * to be invoked if {@link #setReceiveBufferSize} is true.
- */
- private int receiveBufferSize;
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected List getReceived(
+ MultiplexedDatagramSocket socket)
+ {
+ return socket.received;
+ }
+ };
/**
* The list of DatagramPackets to be received through this
@@ -249,30 +117,6 @@ public class MultiplexingDatagramSocket
}
};
- /**
- * The Object which synchronizes the access to {@link #inReceive}.
- */
- private final Object receiveSyncRoot = new Object();
-
- /**
- * The indicator which determines whether
- * {@link DatagramSocket#setReceiveBufferSize(int)} is to be invoked with
- * the value of {@link #receiveBufferSize}.
- */
- private boolean setReceiveBufferSize = false;
-
- /**
- * The MultiplexedDatagramSockets filtering
- * DatagramPackets away from this DatagramSocket.
- */
- private MultiplexedDatagramSocket[] sockets = NO_SOCKETS;
-
- /**
- * The Object which synchronizes the access to the {@link #sockets}
- * field of this instance.
- */
- private final Object socketsSyncRoot = new Object();
-
/**
* Buffer variable for storing the SO_TIMEOUT value set by the
* last setSoTimeout() call. Although not strictly needed,
@@ -378,34 +222,7 @@ public class MultiplexingDatagramSocket
*/
void close(MultiplexedDatagramSocket multiplexed)
{
- synchronized (socketsSyncRoot)
- {
- int socketCount = sockets.length;
-
- for (int i = 0; i < socketCount; i++)
- {
- if (sockets[i].equals(multiplexed))
- {
- if (socketCount == 1)
- {
- sockets = NO_SOCKETS;
- }
- else
- {
- MultiplexedDatagramSocket[] newSockets
- = new MultiplexedDatagramSocket[socketCount - 1];
-
- System.arraycopy(sockets, 0, newSockets, 0, i);
- System.arraycopy(
- sockets, i + 1,
- newSockets, i,
- newSockets.length - i);
- sockets = newSockets;
- }
- break;
- }
- }
- }
+ multiplexingXXXSocketSupport.close(multiplexed);
}
/**
@@ -425,9 +242,9 @@ public class MultiplexingDatagramSocket
* fails
*/
public MultiplexedDatagramSocket getSocket(DatagramPacketFilter filter)
- throws SocketException
+ throws SocketException
{
- return getSocket(filter, true);
+ return getSocket(filter, /* create */ true);
}
/**
@@ -439,9 +256,9 @@ public class MultiplexingDatagramSocket
*
* @param filter the DatagramPacketFilter to get a
* MultiplexedDatagramSocket for
- * @param create whether or not to create a MultiplexedDatagramSocket
- * if this instance does not already have a socket for the given
- * filter.
+ * @param create whether or not to create a
+ * MultiplexedDatagramSocket if this instance does not already have
+ * a socket for the given filter.
* @return a MultiplexedDatagramSocket which filters
* DatagramPackets away from this DatagramSocket using the
* specified filter
@@ -449,35 +266,12 @@ public class MultiplexingDatagramSocket
* MultiplexedDatagramSocket for the specified filter
* fails.
*/
- public MultiplexedDatagramSocket getSocket(DatagramPacketFilter filter,
- boolean create)
+ public MultiplexedDatagramSocket getSocket(
+ DatagramPacketFilter filter,
+ boolean create)
throws SocketException
{
- if (filter == null)
- throw new NullPointerException("filter");
-
- synchronized (socketsSyncRoot)
- {
- // If a socket for the specified filter exists already, do not
- // create a new one and return the existing.
- for (MultiplexedDatagramSocket socket : sockets)
- {
- if (filter.equals(socket.getFilter()))
- return socket;
- }
-
- if (!create)
- return null;
-
- // Create a new socket for the specified filter.
- MultiplexedDatagramSocket socket
- = new MultiplexedDatagramSocket(this, filter);
-
- // Remember the new socket.
- sockets = add(sockets, socket);
-
- return socket;
- }
+ return multiplexingXXXSocketSupport.getSocket(filter, create);
}
/**
@@ -489,6 +283,42 @@ public class MultiplexingDatagramSocket
return soTimeout;
}
+ /**
+ * Implements {@link MultiplexingXXXSocketSupport#doReceive(DatagramPacket)}
+ * on behalf of {@link #multiplexingXXXSocketSupport}. Receives a
+ * {@code DatagramPacket} from this socket.
+ *
+ * @param p the {@code DatagramPacket} into which to place the incoming data
+ * @throws IOException if an I/O error occurs
+ */
+ private void multiplexingXXXSocketSupportDoReceive(DatagramPacket p)
+ throws IOException
+ {
+ super.receive(p);
+ }
+
+ /**
+ * Implements
+ * {@link MultiplexingXXXSocketSupport#doSetReceiveBufferSize(int)} on
+ * behalf of {@link #multiplexingXXXSocketSupport}. Sets the
+ * {@code SO_RCVBUF} option to the specified value for this
+ * {@code DatagramSocket}. The {@code SO_RCVBUF} option is used by the
+ * network implementation as a hint to size the underlying network I/O
+ * buffers. The {@code SO_RCVBUF} setting may also be used by the network
+ * implementation to determine the maximum size of the packet that can be
+ * received on this socket.
+ *
+ * @param receiveBufferSize the size to which to set the receive buffer size
+ * @throws SocketException if there is an error in the underlying protocol,
+ * such as a UDP error
+ */
+ private void multiplexingXXXSocketSupportDoSetReceiveBufferSize(
+ int receiveBufferSize)
+ throws SocketException
+ {
+ super.setReceiveBufferSize(receiveBufferSize);
+ }
+
/**
* Receives a datagram packet from this socket. The DatagramPackets
* returned by this method do not match any of the
@@ -515,181 +345,7 @@ public class MultiplexingDatagramSocket
public void receive(DatagramPacket p)
throws IOException
{
- receive(received, p, soTimeout);
- }
-
- /**
- * Receives a DatagramPacket from a specific list of
- * DatagramPackets if it is not empty or from the network if the
- * specified list is empty. When this method returns, the
- * DatagramPacket's buffer is filled with the data received. The
- * datagram packet also contains the sender's IP address, and the port
- * number on the sender's machine.
- *
- * @param received the list of previously received DatagramPacket
- * from which the first is to be removed and returned if available
- * @param p the DatagramPacket into which to place the incoming
- * data
- * @param timeout the maximum time in milliseconds to wait for a
- * packet. A timeout of zero is interpreted as an infinite
- * timeout
- * @throws IOException if an I/O error occurs
- * @throws SocketTimeoutException if timeout is positive and has
- * expired
- */
- private void receive(
- List received,
- DatagramPacket p,
- int timeout)
- throws IOException
- {
- long startTime = System.currentTimeMillis();
- DatagramPacket r = null;
-
- do
- {
- long now = System.currentTimeMillis();
-
- // If there is a packet which has been received from the network and
- // is to merely be received from the list of received
- // DatagramPackets, then let it be received and do not throw a
- // SocketTimeoutException.
- synchronized (received)
- {
- if (!received.isEmpty())
- {
- r = received.remove(0);
- if (r != null)
- break;
- }
- }
-
- // Throw a SocketTimeoutException if the timeout is over/up.
- long remainingTimeout;
-
- if (timeout > 0)
- {
- remainingTimeout = timeout - (now - startTime);
- if (remainingTimeout <= 0L)
- {
- throw new SocketTimeoutException(
- Long.toString(remainingTimeout));
- }
- }
- else
- {
- remainingTimeout = 1000L;
- }
-
- // Determine whether the caller will receive from the network or
- // will wait for a previous caller to receive from the network.
- boolean wait;
-
- synchronized (receiveSyncRoot)
- {
- if (inReceive)
- {
- wait = true;
- }
- else
- {
- wait = false;
- inReceive = true;
- }
- }
- try
- {
- if (wait)
- {
- // The caller will wait for a previous caller to receive
- // from the network.
- synchronized (received)
- {
- if (received.isEmpty())
- {
- try
- {
- received.wait(remainingTimeout);
- }
- catch (InterruptedException ie)
- {
- }
- }
- else
- {
- received.notifyAll();
- }
- }
- continue;
- }
-
- // The caller will receive from the network.
- DatagramPacket c = clone(p, /* arraycopy */ false);
-
- synchronized (receiveSyncRoot)
- {
- if (setReceiveBufferSize)
- {
- setReceiveBufferSize = false;
- try
- {
- super.setReceiveBufferSize(receiveBufferSize);
- }
- catch (Throwable t)
- {
- if (t instanceof ThreadDeath)
- throw (ThreadDeath) t;
- }
- }
- }
- super.receive(c);
-
- // The caller received from the network. Copy/add the packet to
- // the receive list of the sockets which accept it.
- synchronized (socketsSyncRoot)
- {
- boolean accepted = false;
-
- for (MultiplexedDatagramSocket socket : sockets)
- {
- if (socket.getFilter().accept(c))
- {
- synchronized (socket.received)
- {
- socket.received.add(
- accepted
- ? clone(c, /* arraycopy */ true)
- : c);
- socket.received.notifyAll();
- }
- accepted = true;
-
- // Emil: Don't break because we want all filtering
- // sockets to get the received packet.
- }
- }
- if (!accepted)
- {
- synchronized (this.received)
- {
- this.received.add(c);
- this.received.notifyAll();
- }
- }
- }
- }
- finally
- {
- synchronized (receiveSyncRoot)
- {
- if (!wait)
- inReceive = false;
- }
- }
- }
- while (true);
-
- copy(r, p);
+ multiplexingXXXSocketSupport.receive(received, p, soTimeout);
}
/**
@@ -706,7 +362,10 @@ public class MultiplexingDatagramSocket
void receive(MultiplexedDatagramSocket multiplexed, DatagramPacket p)
throws IOException
{
- receive(multiplexed.received, p, multiplexed.getSoTimeout());
+ multiplexingXXXSocketSupport.receive(
+ multiplexed.received,
+ p,
+ multiplexed.getSoTimeout());
}
/**
@@ -716,21 +375,7 @@ public class MultiplexingDatagramSocket
public void setReceiveBufferSize(int receiveBufferSize)
throws SocketException
{
- synchronized (receiveSyncRoot)
- {
- this.receiveBufferSize = receiveBufferSize;
-
- if (inReceive)
- {
- setReceiveBufferSize = true;
- }
- else
- {
- super.setReceiveBufferSize(receiveBufferSize);
-
- setReceiveBufferSize = false;
- }
- }
+ multiplexingXXXSocketSupport.setReceiveBufferSize(receiveBufferSize);
}
/**
diff --git a/src/main/java/org/ice4j/socket/MultiplexingSocket.java b/src/main/java/org/ice4j/socket/MultiplexingSocket.java
index 7f896e9..7a2831b 100644
--- a/src/main/java/org/ice4j/socket/MultiplexingSocket.java
+++ b/src/main/java/org/ice4j/socket/MultiplexingSocket.java
@@ -41,26 +41,73 @@ public class MultiplexingSocket
private static final Logger logger
= Logger.getLogger(MultiplexingSocket.class.getName());
- /**
- * The constant which represents an empty array with
- * MultiplexedSocket element type. Explicitly defined in order to
- * reduce allocations.
- */
- private static final MultiplexedSocket[] NO_SOCKETS
- = new MultiplexedSocket[0];
-
/**
* Custom InputStream for this Socket.
*/
private final InputStream inputStream = new TCPInputStream(this);
/**
- * The indicator which determines whether this Socket is currently
- * reading from the network using {@link #receive(DatagramPacket)}. When
- * true, subsequent requests to read from the network will be
- * blocked until the current read is finished.
+ * The {@code MultiplexingXXXSocketSupport} which implements functionality
+ * common to TCP and UDP sockets in order to facilitate implementers such as
+ * this instance.
*/
- private boolean inReceive = false;
+ private final MultiplexingXXXSocketSupport
+ multiplexingXXXSocketSupport
+ = new MultiplexingXXXSocketSupport(
+ MultiplexedSocket.class)
+ {
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected MultiplexedSocket createSocket(
+ DatagramPacketFilter filter)
+ throws SocketException
+ {
+ return
+ new MultiplexedSocket(MultiplexingSocket.this, filter);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected void doReceive(DatagramPacket p)
+ throws IOException
+ {
+ multiplexingXXXSocketSupportDoReceive(p);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected void doSetReceiveBufferSize(int receiveBufferSize)
+ throws SocketException
+ {
+ multiplexingXXXSocketSupportDoSetReceiveBufferSize(
+ receiveBufferSize);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected List getReceived()
+ {
+ return received;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected List getReceived(
+ MultiplexedSocket socket)
+ {
+ return socket.received;
+ }
+ };
/**
* Custom OutputStream for this Socket.
@@ -86,23 +133,6 @@ public class MultiplexingSocket
}
};
- /**
- * The Object which synchronizes the access to {@link #inReceive}.
- */
- private final Object receiveSyncRoot = new Object();
-
- /**
- * The MultiplexedSockets filtering DatagramPackets away
- * from this Socket.
- */
- private MultiplexedSocket[] sockets = NO_SOCKETS;
-
- /**
- * The Object which synchronizes the access to the {@link #sockets}
- * field of this instance.
- */
- private final Object socketsSyncRoot = new Object();
-
/**
* Buffer variable for storing the SO_TIMEOUT value set by the last
* setSoTimeout() call. Although not strictly needed, getting the
@@ -227,34 +257,7 @@ public class MultiplexingSocket
*/
void close(MultiplexedSocket multiplexed)
{
- synchronized (socketsSyncRoot)
- {
- int socketCount = sockets.length;
-
- for (int i = 0; i < socketCount; i++)
- {
- if (sockets[i].equals(multiplexed))
- {
- if (socketCount == 1)
- {
- sockets = NO_SOCKETS;
- }
- else
- {
- MultiplexedSocket[] newSockets
- = new MultiplexedSocket[socketCount - 1];
-
- System.arraycopy(sockets, 0, newSockets, 0, i);
- System.arraycopy(
- sockets, i + 1,
- newSockets, i,
- newSockets.length - i);
- sockets = newSockets;
- }
- break;
- }
- }
- }
+ multiplexingXXXSocketSupport.close(multiplexed);
}
/**
@@ -322,27 +325,7 @@ public class MultiplexingSocket
public MultiplexedSocket getSocket(DatagramPacketFilter filter)
throws SocketException
{
- if (filter == null)
- throw new NullPointerException("filter");
-
- synchronized (socketsSyncRoot)
- {
- // If a socket for the specified filter exists already, do not
- // create a new one and return the existing.
- for (MultiplexedSocket socket : sockets)
- {
- if (filter.equals(socket.getFilter()))
- return socket;
- }
-
- // Create a new socket for the specified filter.
- MultiplexedSocket socket = new MultiplexedSocket(this, filter);
-
- // Remember the new socket.
- sockets = MultiplexingDatagramSocket.add(sockets, socket);
-
- return socket;
- }
+ return multiplexingXXXSocketSupport.getSocket(filter);
}
/**
@@ -354,6 +337,42 @@ public class MultiplexingSocket
return soTimeout;
}
+ /**
+ * Implements {@link MultiplexingXXXSocketSupport#doReceive(DatagramPacket)}
+ * on behalf of {@link #multiplexingXXXSocketSupport}. Receives a
+ * {@code DatagramPacket} from this socket.
+ *
+ * @param p the {@code DatagramPacket} into which to place the incoming data
+ * @throws IOException if an I/O error occurs
+ */
+ private void multiplexingXXXSocketSupportDoReceive(DatagramPacket p)
+ throws IOException
+ {
+ super.receive(p);
+ }
+
+ /**
+ * Implements
+ * {@link MultiplexingXXXSocketSupport#doSetReceiveBufferSize(int)} on
+ * behalf of {@link #multiplexingXXXSocketSupport}. Sets the
+ * {@code SO_RCVBUF} option to the specified value for this
+ * {@code DatagramSocket}. The {@code SO_RCVBUF} option is used by the
+ * network implementation as a hint to size the underlying network I/O
+ * buffers. The {@code SO_RCVBUF} setting may also be used by the network
+ * implementation to determine the maximum size of the packet that can be
+ * received on this socket.
+ *
+ * @param receiveBufferSize the size to which to set the receive buffer size
+ * @throws SocketException if there is an error in the underlying protocol,
+ * such as a TCP error
+ */
+ private void multiplexingXXXSocketSupportDoSetReceiveBufferSize(
+ int receiveBufferSize)
+ throws SocketException
+ {
+ super.setReceiveBufferSize(receiveBufferSize);
+ }
+
/**
* Receives a datagram packet from this socket. The DatagramPackets
* returned by this method do not match any of the
@@ -385,168 +404,8 @@ public class MultiplexingSocket
catch(Exception e)
{
}
- receive(received, p, soTimeout);
- }
- /**
- * Receives a DatagramPacket from a specific list of
- * DatagramPackets if it is not empty or from the network if the
- * specified list is empty. When this method returns, the
- * DatagramPacket's buffer is filled with the data received. The
- * datagram packet also contains the sender's IP address, and the port
- * number on the sender's machine.
- *
- * @param received the list of previously received DatagramPacket
- * from which the first is to be removed and returned if available
- * @param p the DatagramPacket into which to place the incoming
- * data
- * @param timeout the maximum time in milliseconds to wait for a
- * packet. A timeout of zero is interpreted as an infinite
- * timeout
- * @throws SocketTimeoutException if the timeout has expired
- * @throws IOException if an I/O error occurs
- */
- private void receive(List received,
- DatagramPacket p,
- int timeout)
- throws IOException
- {
- long startTime = System.currentTimeMillis();
- DatagramPacket r = null;
-
- do
- {
- long now = System.currentTimeMillis();
-
- // If there is a packet which has been received from the network and
- // is to merely be received from the list of received
- // DatagramPackets, then let it be received and do not throw a
- // SocketTimeoutException.
- synchronized (received)
- {
- if (!received.isEmpty())
- {
- r = received.remove(0);
- if (r != null)
- break;
- }
- }
-
- // Throw a SocketTimeoutException if the timeout is over/up.
- long remainingTimeout;
-
- if (timeout > 0)
- {
- remainingTimeout = timeout - (now - startTime);
- if (remainingTimeout <= 0L)
- {
- throw new SocketTimeoutException(
- Long.toString(remainingTimeout));
- }
- }
- else
- {
- remainingTimeout = 1000L;
- }
-
- // Determine whether the caller will receive from the network or
- // will wait for a previous caller to receive from the network.
- boolean wait;
-
- synchronized (receiveSyncRoot)
- {
- if (inReceive)
- {
- wait = true;
- }
- else
- {
- wait = false;
- inReceive = true;
- }
- }
- try
- {
- if (wait)
- {
- // The caller will wait for a previous caller to receive
- // from the network.
- synchronized (received)
- {
- if (received.isEmpty())
- {
- try
- {
- received.wait(remainingTimeout);
- }
- catch (InterruptedException ie)
- {
- }
- }
- else
- {
- received.notifyAll();
- }
- }
- continue;
- }
-
- // The caller will receive from the network.
- DatagramPacket c
- = MultiplexingDatagramSocket.clone(
- p,
- /* arraycopy */ false);
-
- super.receive(c);
-
- // The caller received from the network. Copy/add the packet to
- // the receive list of the sockets which accept it.
- synchronized (socketsSyncRoot)
- {
- boolean accepted = false;
-
- for (MultiplexedSocket socket : sockets)
- {
- if (socket.getFilter().accept(c))
- {
- synchronized (socket.received)
- {
- socket.received.add(
- accepted
- ? MultiplexingDatagramSocket.clone(
- c,
- /* arraycopy */ true)
- : c);
- socket.received.notifyAll();
- }
- accepted = true;
-
- // Emil Ivov: Don't break because we want all
- // filtering sockets to get the received packet.
- }
- }
- if (!accepted)
- {
- synchronized (this.received)
- {
- this.received.add(c);
- this.received.notifyAll();
- }
- }
- }
- }
- finally
- {
- synchronized (receiveSyncRoot)
- {
- if (!wait)
- inReceive = false;
- }
- }
- }
- while (true);
-
- MultiplexingDatagramSocket.copy(r, p);
+ multiplexingXXXSocketSupport.receive(received, p, soTimeout);
}
/**
@@ -568,7 +427,11 @@ public class MultiplexingSocket
catch(Exception e)
{
}
- receive(multiplexed.received, p, multiplexed.getSoTimeout());
+
+ multiplexingXXXSocketSupport.receive(
+ multiplexed.received,
+ p,
+ multiplexed.getSoTimeout());
}
/**
diff --git a/src/main/java/org/ice4j/socket/MultiplexingXXXSocketSupport.java b/src/main/java/org/ice4j/socket/MultiplexingXXXSocketSupport.java
new file mode 100644
index 0000000..28ee966
--- /dev/null
+++ b/src/main/java/org/ice4j/socket/MultiplexingXXXSocketSupport.java
@@ -0,0 +1,773 @@
+/*
+ * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
+ *
+ * Copyright @ 2015 Atlassian Pty Ltd
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.ice4j.socket;
+
+import java.io.*;
+import java.lang.reflect.*;
+import java.net.*;
+import java.util.*;
+import java.util.logging.*;
+
+/**
+ * Implements functionality common to TCP and UDP implementations of
+ * (de)multiplexing sockets i.e. sockets which provide
+ * {@code DatagramPacket}-based views of the packets they receive in the forms
+ * of pseudo sockets.
+ *
+ * @author Lyubomir Marinov
+ */
+abstract class MultiplexingXXXSocketSupport
+
+{
+ /**
+ * The {@code Logger} used by the {@code MultiplexingXXXSocketSupport} class
+ * and its instances for logging output.
+ */
+ private static final Logger logger
+ = Logger.getLogger(MultiplexingXXXSocketSupport.class.getName());
+
+ /**
+ * Adds/appends a new element to an existing array.
+ *
+ * @param the component type of {@code array} and the type of
+ * {@code element}
+ * @param array the array to which {@code element} is to be added/appended
+ * @param element the new element to add/append to {@code array}
+ * @return an array which is a concatenation of {@code array} and
+ * {@code element}
+ */
+ static T[] add(T[] array, T element)
+ {
+ int length = array.length;
+ @SuppressWarnings("unchecked")
+ T[] newArray
+ = (T[])
+ Array.newInstance(
+ array.getClass().getComponentType(),
+ length + 1);
+
+ if (length != 0)
+ {
+ System.arraycopy(array, 0, newArray, 0, length);
+ }
+ newArray[length] = element;
+ return newArray;
+ }
+
+ /**
+ * Initializes a new DatagramPacket instance which is a clone of a
+ * specific DatagramPacket i.e. the properties of the clone
+ * DatagramPacket are clones of the specified
+ * DatagramPacket.
+ *
+ * @param p the DatagramPacket to clone
+ * @return a new DatagramPacket instance which is a clone of the
+ * specified DatagramPacket
+ */
+ public static DatagramPacket clone(DatagramPacket p)
+ {
+ return clone(p, /* arraycopy */ true);
+ }
+
+ /**
+ * Initializes a new DatagramPacket instance which is a clone of a
+ * specific DatagramPacket i.e. the properties of the clone
+ * DatagramPacket are clones of the specified
+ * DatagramPacket.
+ *
+ * @param p the DatagramPacket to clone
+ * @param arraycopy true if the actual bytes of the data of
+ * p are to be copied into the clone or false if only the
+ * capacity of the data of p is to be cloned without copying the
+ * actual bytes of the data of p
+ * @return a new DatagramPacket instance which is a clone of the
+ * specified DatagramPacket
+ */
+ private static DatagramPacket clone(DatagramPacket p, boolean arraycopy)
+ {
+ byte[] data;
+ int off;
+ int len;
+ InetAddress address;
+ int port;
+
+ synchronized (p)
+ {
+ data = p.getData();
+ off = p.getOffset();
+ len = p.getLength();
+
+ // Clone the data.
+ {
+ // The capacity of the specified p is preserved.
+ byte[] dataClone = new byte[data.length];
+
+ // However, only copy the range of data starting with off and
+ // spanning len number of bytes. Of course, preserve off and len
+ // in addition to the capacity.
+ if (arraycopy && (len > 0))
+ {
+ int arraycopyOff, arraycopyLen;
+
+ // If off and/or len are going to cause an exception though,
+ // copy the whole data.
+ if ((off >= 0)
+ && (off < data.length)
+ && (off + len <= data.length))
+ {
+ arraycopyOff = off;
+ arraycopyLen = len;
+ }
+ else
+ {
+ arraycopyOff = 0;
+ arraycopyLen = data.length;
+ }
+ System.arraycopy(
+ data, arraycopyOff,
+ dataClone, arraycopyOff,
+ arraycopyLen);
+ }
+ data = dataClone;
+ }
+
+ address = p.getAddress();
+ port = p.getPort();
+ }
+
+ DatagramPacket c = new DatagramPacket(data, off, len);
+
+ if (address != null)
+ c.setAddress(address);
+ if (port >= 0)
+ c.setPort(port);
+
+ return c;
+ }
+
+ /**
+ * Copies the properties of a specific DatagramPacket to another
+ * DatagramPacket. The property values are not cloned.
+ *
+ * @param src the DatagramPacket which is to have its properties
+ * copied to dest
+ * @param dest the DatagramPacket which is to have its properties
+ * set to the value of the respective properties of src
+ */
+ public static void copy(DatagramPacket src, DatagramPacket dest)
+ {
+ synchronized (dest)
+ {
+ dest.setAddress(src.getAddress());
+ dest.setPort(src.getPort());
+
+ byte[] srcData = src.getData();
+
+ if (srcData == null)
+ {
+ dest.setLength(0);
+ }
+ else
+ {
+ byte[] destData = dest.getData();
+
+ if (destData == null)
+ {
+ dest.setLength(0);
+ }
+ else
+ {
+ int destOffset = dest.getOffset();
+ int destLength = destData.length - destOffset;
+ int srcLength = src.getLength();
+
+ if (destLength >= srcLength)
+ {
+ destLength = srcLength;
+ }
+ else if (logger.isLoggable(Level.WARNING))
+ {
+ logger.log(
+ Level.WARNING,
+ "Truncating received DatagramPacket data!");
+ }
+ System.arraycopy(
+ srcData, src.getOffset(),
+ destData, destOffset,
+ destLength);
+ dest.setLength(destLength);
+ }
+ }
+ }
+ }
+
+ /**
+ * The indicator which determines whether this DatagramSocket is
+ * currently reading from the network using
+ * {@link DatagramSocket#receive(DatagramPacket)}. When true,
+ * subsequent requests to read from the network will be blocked until the
+ * current read is finished.
+ */
+ private boolean inReceive = false;
+
+ /**
+ * The {@code Class} of the multiplexed sockets supported by this instance.
+ */
+ private final Class multiplexedXXXSocketClass;
+
+ /**
+ * The constant which represents an empty array with
+ * MultiplexedDatagramSocket element type. Explicitly defined in
+ * order to reduce allocations.
+ */
+ private final MultiplexedXXXSocketT[] NO_SOCKETS;
+
+ /**
+ * The value with which {@link DatagramSocket#setReceiveBufferSize(int)} is
+ * to be invoked if {@link #setReceiveBufferSize} is true.
+ */
+ private int receiveBufferSize;
+
+ /**
+ * The Object which synchronizes the access to {@link #inReceive}.
+ */
+ private final Object receiveSyncRoot = new Object();
+
+ /**
+ * The indicator which determines whether
+ * {@link DatagramSocket#setReceiveBufferSize(int)} is to be invoked with
+ * the value of {@link #receiveBufferSize}.
+ */
+ private boolean setReceiveBufferSize = false;
+
+ /**
+ * The IP sockets filtering {@code DatagramPacket}s away from this IP
+ * socket.
+ */
+ private MultiplexedXXXSocketT[] sockets;
+
+ /**
+ * The {@code Object} which synchronizes the access to the {@link #sockets}
+ * field of this instance.
+ */
+ private final Object socketsSyncRoot = new Object();
+
+ /**
+ * Initializes a new {@code MultiplexingXXXSocketSupport} instance.
+ *
+ * @param multiplexedXXXSocketClass the {@code Class} of the multiplexed
+ * sockets supported by the new instance
+ */
+ protected MultiplexingXXXSocketSupport(
+ Class multiplexedXXXSocketClass)
+ {
+ this.multiplexedXXXSocketClass = multiplexedXXXSocketClass;
+
+ NO_SOCKETS
+ = (MultiplexedXXXSocketT[])
+ Array.newInstance(multiplexedXXXSocketClass, 0);
+ sockets = NO_SOCKETS;
+ }
+
+ /**
+ * Accepts a {@code DatagramPacket} received by this socket and queues it
+ * for receipt through either this multiplexing socket or its multiplexed
+ * sockets whose {@code DatagramPacketFilter}s accept {@code p}.
+ *
+ * @param p the {@code DatagramPacket} to be accepted by either this
+ * multiplexing socket or its multiplexed sockets whose
+ * {@code DatagramPacketFilter}s accept {@code p}
+ */
+ private void acceptBySocketsOrThis(DatagramPacket p)
+ {
+ synchronized (socketsSyncRoot)
+ {
+ boolean accepted = false;
+
+ for (MultiplexedXXXSocketT socket : sockets)
+ {
+ if (getFilter(socket).accept(p))
+ {
+ List socketReceived = getReceived(socket);
+
+ synchronized (socketReceived)
+ {
+ socketReceived.add(
+ accepted ? clone(p, /* arraycopy */ true) : p);
+ socketReceived.notifyAll();
+ }
+ accepted = true;
+
+ // Emil Ivov: Don't break because we want all
+ // filtering sockets to get the received packet.
+ }
+ }
+ if (!accepted)
+ {
+ List thisReceived = getReceived();
+
+ synchronized (thisReceived)
+ {
+ thisReceived.add(p);
+ thisReceived.notifyAll();
+ }
+ }
+ }
+ }
+
+ /**
+ * Closes a specific MultiplexedDatagramSocket which filters
+ * DatagramPackets away from this DatagramSocket.
+ *
+ * @param multiplexed the MultiplexedDatagramSocket to close
+ */
+ void close(MultiplexedXXXSocketT multiplexed)
+ {
+ synchronized (socketsSyncRoot)
+ {
+ int socketCount = sockets.length;
+
+ for (int i = 0; i < socketCount; i++)
+ {
+ if (sockets[i].equals(multiplexed))
+ {
+ if (socketCount == 1)
+ {
+ sockets = NO_SOCKETS;
+ }
+ else
+ {
+ MultiplexedXXXSocketT[] newSockets
+ = (MultiplexedXXXSocketT[])
+ Array.newInstance(
+ multiplexedXXXSocketClass,
+ socketCount - 1);
+
+ System.arraycopy(sockets, 0, newSockets, 0, i);
+ System.arraycopy(
+ sockets, i + 1,
+ newSockets, i,
+ newSockets.length - i);
+ sockets = newSockets;
+ }
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Initializes a new multiplexed socket instance which is to be associated
+ * with a specific {@code DatagramPacketFilter}.
+ *
+ * @param filter the {@code DatagramPacketFilter} to associate with the new
+ * instance
+ * @return a new multiplexed socket associated with the specified
+ * {@code filter}
+ * @throws SocketException if there is an error in the underlying protocol,
+ * such as a TCP or UDP error
+ */
+ protected abstract MultiplexedXXXSocketT createSocket(
+ DatagramPacketFilter filter)
+ throws SocketException;
+
+ /**
+ * Receives a {@code DatagramPacket} from this socket.
+ *
+ * @param p the {@code DatagramPacket} into which to place the incoming data
+ * @throws IOException if an I/O error occurs
+ */
+ protected abstract void doReceive(DatagramPacket p)
+ throws IOException;
+
+ /**
+ * Sets the {@code SO_RCVBUF} option to the specified value for this
+ * {@code DatagramSocket}. The {@code SO_RCVBUF} option is used by the
+ * network implementation as a hint to size the underlying network I/O
+ * buffers. The {@code SO_RCVBUF} setting may also be used by the network
+ * implementation to determine the maximum size of the packet that can be
+ * received on this socket.
+ *
+ * @param receiveBufferSize the size to which to set the receive buffer size
+ * @throws SocketException if there is an error in the underlying protocol,
+ * such as a UDP error
+ */
+ protected abstract void doSetReceiveBufferSize(int receiveBufferSize)
+ throws SocketException;
+
+ /**
+ * Gets the {@code DatagramPacketFilter} associated with a specific
+ * multiplexed socket.
+ *
+ * @param socket the multiplexed socket whose associated
+ * {@code DatagramPacketFilter} is to be retrieved
+ * @return the {@code DatagramPacketFilter} associated with {@code socket}
+ */
+ protected DatagramPacketFilter getFilter(MultiplexedXXXSocketT socket)
+ {
+ return socket.getFilter();
+ }
+
+ /**
+ * Gets the list of {@code DatagramPacket}s received by this socket and not
+ * accepted by any (existing) {@code DatagramPacketFilter} at the time of
+ * receipt.
+ *
+ * @return the list of {@code DatagramPacket}s received by this socket and
+ * not accepted by any (existing) {@code DatagramPacketFilter} at the time of
+ * receipt
+ */
+ protected abstract List getReceived();
+
+ /**
+ * Gets the list of {@code DatagramPacket}s received by this multiplexing
+ * socket and accepted by the {@code DatagramPacketFilter} of a specific
+ * multiplexed socket at the time of receipt.
+ *
+ * @param socket the multiplexed socket whose list of accepted received
+ * {@code DatagramPacket}s is to be returned
+ * @return the list of {@code DatagramPacket}s received by this multiplexing
+ * socket and accepted by the {@code DatagramPacketFilter} of the
+ * multiplexed {@code socket} at the time of receipt
+ */
+ protected abstract List getReceived(
+ MultiplexedXXXSocketT socket);
+
+ /**
+ * Gets a MultiplexedDatagramSocket which filters
+ * DatagramPackets away from this DatagramSocket using a
+ * specific DatagramPacketFilter. If such a
+ * MultiplexedDatagramSocket does not exist in this instance, it is
+ * created.
+ *
+ * @param filter the DatagramPacketFilter to get a
+ * MultiplexedDatagramSocket for
+ * @return a MultiplexedDatagramSocket which filters
+ * DatagramPackets away from this DatagramSocket using the
+ * specified filter
+ * @throws SocketException if creating the
+ * MultiplexedDatagramSocket for the specified filter
+ * fails
+ */
+ public MultiplexedXXXSocketT getSocket(DatagramPacketFilter filter)
+ throws SocketException
+ {
+ return getSocket(filter, /* create */ true);
+ }
+
+ /**
+ * Gets a MultiplexedDatagramSocket which filters
+ * DatagramPackets away from this DatagramSocket using a
+ * specific DatagramPacketFilter. If create is true and
+ * such a MultiplexedDatagramSocket does not exist in this
+ * instance, it is created.
+ *
+ * @param filter the DatagramPacketFilter to get a
+ * MultiplexedDatagramSocket for
+ * @param create whether or not to create a
+ * MultiplexedDatagramSocket if this instance does not already have
+ * a socket for the given filter.
+ * @return a MultiplexedDatagramSocket which filters
+ * DatagramPackets away from this DatagramSocket using the
+ * specified filter
+ * @throws SocketException if creating the
+ * MultiplexedDatagramSocket for the specified filter
+ * fails.
+ */
+ public MultiplexedXXXSocketT getSocket(
+ DatagramPacketFilter filter,
+ boolean create)
+ throws SocketException
+ {
+ if (filter == null)
+ throw new NullPointerException("filter");
+
+ synchronized (socketsSyncRoot)
+ {
+ // If a socket for the specified filter exists already, do not
+ // create a new one and return the existing.
+ for (MultiplexedXXXSocketT socket : sockets)
+ {
+ if (filter.equals(getFilter(socket)))
+ return socket;
+ }
+
+ if (!create)
+ return null;
+
+ // Create a new socket for the specified filter.
+ MultiplexedXXXSocketT socket = createSocket(filter);
+
+ // Remember the new socket.
+ if (socket != null)
+ {
+ sockets = add(sockets, socket);
+
+ // A multiplexed socket may be created after packets matching
+ // its filter have been received. Pull them out of the
+ // multiplexing socket and into the newly-created multiplexed
+ // socket.
+
+ // XXX The fields received of both the multiplexed and the
+ // multiplexing sockets are used as synchronization roots (e.g.
+ // the method acceptBySocketsOrThis). In order to preserve the
+ // order of acquiring synchronization roots, perform the
+ // following procedure under the protection of the field
+ // socketsSyncRoot even though the field sockets will not be
+ // accessed.
+ moveReceivedFromThisToSocket(socket);
+ }
+
+ return socket;
+ }
+ }
+
+ /**
+ * Moves packets which have been received from this multiplexing socket to
+ * a specific multiplexed socket if they are accepted by the
+ * {@code DatagramPacketFilter} of the latter.
+ *
+ * @param socket the multiplexed socket into which received packets are to
+ * be moved from this multiplexing socket if they are accepted by the
+ * {@code DatagramPacketFilter} of the former
+ */
+ private void moveReceivedFromThisToSocket(MultiplexedXXXSocketT socket)
+ {
+ // Pull the packets which have been received already and are accepted by
+ // the specified multiplexed socket out of the multiplexing socket.
+ List thisReceived = getReceived();
+ DatagramPacketFilter socketFilter = getFilter(socket);
+ List toMove = null;
+
+ synchronized (thisReceived)
+ {
+ if (thisReceived.isEmpty())
+ {
+ return;
+ }
+ else
+ {
+ for (Iterator i = thisReceived.iterator();
+ i.hasNext();)
+ {
+ DatagramPacket p = i.next();
+
+ if (socketFilter.accept(p))
+ {
+ if (toMove == null)
+ toMove = new LinkedList();
+ toMove.add(p);
+
+ // XXX In the method receive, we allow multiple filters
+ // to accept one and the same packet.
+ i.remove();
+ }
+ }
+ }
+ }
+
+ // Push the packets which have been accepted already and are accepted by
+ // the specified multiplexed socket into the multiplexed socket in
+ // question.
+ if (toMove != null)
+ {
+ List socketReceived = getReceived(socket);
+
+ synchronized (socketReceived)
+ {
+ socketReceived.addAll(toMove);
+ // The notifyAll will practically likely be unnecessary because
+ // the specified socket will likely be a newly-created one to
+ // which noone else has a reference. Anyway, dp the invocation
+ // for the purposes of consistency, clarity, and such.
+ socketReceived.notifyAll();
+ }
+ }
+ }
+
+ /**
+ * Receives a DatagramPacket from a specific list of
+ * DatagramPackets if it is not empty or from the network if the
+ * specified list is empty. When this method returns, the
+ * DatagramPacket's buffer is filled with the data received. The
+ * datagram packet also contains the sender's IP address, and the port
+ * number on the sender's machine.
+ *
+ * @param received the list of previously received DatagramPacket
+ * from which the first is to be removed and returned if available
+ * @param p the DatagramPacket into which to place the incoming
+ * data
+ * @param timeout the maximum time in milliseconds to wait for a
+ * packet. A timeout of zero is interpreted as an infinite
+ * timeout
+ * @throws IOException if an I/O error occurs
+ * @throws SocketTimeoutException if timeout is positive and has
+ * expired
+ */
+ void receive(List received, DatagramPacket p, int timeout)
+ throws IOException
+ {
+ long startTime = System.currentTimeMillis();
+ DatagramPacket r = null;
+
+ do
+ {
+ long now = System.currentTimeMillis();
+
+ // If there is a packet which has been received from the network and
+ // is to merely be received from the list of received
+ // DatagramPackets, then let it be received and do not throw a
+ // SocketTimeoutException.
+ synchronized (received)
+ {
+ if (!received.isEmpty())
+ {
+ r = received.remove(0);
+ if (r != null)
+ break;
+ }
+ }
+
+ // Throw a SocketTimeoutException if the timeout is over/up.
+ long remainingTimeout;
+
+ if (timeout > 0)
+ {
+ remainingTimeout = timeout - (now - startTime);
+ if (remainingTimeout <= 0L)
+ {
+ throw new SocketTimeoutException(
+ Long.toString(remainingTimeout));
+ }
+ }
+ else
+ {
+ remainingTimeout = 1000L;
+ }
+
+ // Determine whether the caller will receive from the network or
+ // will wait for a previous caller to receive from the network.
+ boolean wait;
+
+ synchronized (receiveSyncRoot)
+ {
+ if (inReceive)
+ {
+ wait = true;
+ }
+ else
+ {
+ wait = false;
+ inReceive = true;
+ }
+ }
+ try
+ {
+ if (wait)
+ {
+ // The caller will wait for a previous caller to receive
+ // from the network.
+ synchronized (received)
+ {
+ if (received.isEmpty())
+ {
+ try
+ {
+ received.wait(remainingTimeout);
+ }
+ catch (InterruptedException ie)
+ {
+ }
+ }
+ else
+ {
+ received.notifyAll();
+ }
+ }
+ continue;
+ }
+
+ // The caller will receive from the network.
+ DatagramPacket c = clone(p, /* arraycopy */ false);
+
+ synchronized (receiveSyncRoot)
+ {
+ if (setReceiveBufferSize)
+ {
+ setReceiveBufferSize = false;
+ try
+ {
+ doSetReceiveBufferSize(receiveBufferSize);
+ }
+ catch (Throwable t)
+ {
+ if (t instanceof ThreadDeath)
+ throw (ThreadDeath) t;
+ }
+ }
+ }
+ doReceive(c);
+
+ // The caller received from the network. Copy/add the packet to
+ // the receive list of the sockets which accept it.
+ acceptBySocketsOrThis(c);
+ }
+ finally
+ {
+ synchronized (receiveSyncRoot)
+ {
+ if (!wait)
+ inReceive = false;
+ }
+ }
+ }
+ while (true);
+
+ copy(r, p);
+ }
+
+ /**
+ * Sets the {@code SO_RCVBUF} option to the specified value for this socket.
+ * The {@code SO_RCVBUF} option is used by the network implementation as a
+ * hint to size the underlying network I/O buffers. The {@code SO_RCVBUF}
+ * setting may also be used by the network implementation to determine the
+ * maximum size of the packet that can be received on this socket.
+ *
+ * @param receiveBufferSize the size to which to set the receive buffer size
+ * @throws SocketException if there is an error in the underlying protocol,
+ * such as a TCP or UDP error
+ */
+ public void setReceiveBufferSize(int receiveBufferSize)
+ throws SocketException
+ {
+ synchronized (receiveSyncRoot)
+ {
+ this.receiveBufferSize = receiveBufferSize;
+
+ if (inReceive)
+ {
+ setReceiveBufferSize = true;
+ }
+ else
+ {
+ doSetReceiveBufferSize(receiveBufferSize);
+ setReceiveBufferSize = false;
+ }
+ }
+ }
+}
diff --git a/src/main/java/org/ice4j/socket/RelayedCandidateDatagramSocket.java b/src/main/java/org/ice4j/socket/RelayedCandidateDatagramSocket.java
index 94c267e..77dfb63 100644
--- a/src/main/java/org/ice4j/socket/RelayedCandidateDatagramSocket.java
+++ b/src/main/java/org/ice4j/socket/RelayedCandidateDatagramSocket.java
@@ -734,7 +734,7 @@ public class RelayedCandidateDatagramSocket
{
DatagramPacket packetToReceive = packetsToReceive.remove(0);
- MultiplexingDatagramSocket.copy(packetToReceive, p);
+ MultiplexingXXXSocketSupport.copy(packetToReceive, p);
packetsToReceive.notifyAll();
break;
}
@@ -1072,7 +1072,7 @@ public class RelayedCandidateDatagramSocket
}
else
{
- packetsToSend.add(MultiplexingDatagramSocket.clone(p));
+ packetsToSend.add(MultiplexingXXXSocketSupport.clone(p));
if (sendThread == null)
createSendThread();
else