entry : channels.entrySet())
- {
- if (now - entry.getValue() > READ_TIMEOUT)
- {
- SocketChannel channel = entry.getKey();
-
- toRemove.add(channel);
- logger.info("Read timeout for socket: " + channel);
-
- try
- {
- channel.close();
- }
- catch (IOException ioe)
- {
- logger.info("Failed to close channel: " + ioe);
- }
-
- }
- }
-
- for (SocketChannel channel : toRemove)
- {
- channels.remove(channel);
- }
- }
-
- /**
- * Tries to read a STUN message from a specific SocketChannel
- * and handles the channel accordingly.
- *
- * If a STUN message is successfully read, and it contains a USERNAME
- * attribute, the local "ufrag" is extracted from the attribute value
- * and the socket is passed on to the Component that
- * this MultiplexingTcpHostHarvester has associated with that
- * "ufrag".
- * @param channel the SocketChannel to read from.
- */
- private void readFromChannel(SocketChannel channel)
- {
- try
- {
- // re-enable blocking mode, so that we can read from the
- // socket's input stream
- channel.configureBlocking(true);
-
- Socket socket = channel.socket();
- InputStream inputStream = socket.getInputStream();
-
- // If we use ssltcp we wait for a pseudo-ssl handshake from the
- // client.
- if (ssltcp)
- {
- byte[] buf
- = new byte[GoogleTurnSSLCandidateHarvester
- .SSL_CLIENT_HANDSHAKE.length];
-
- inputStream.read(buf);
- if (Arrays.equals(buf,
- GoogleTurnSSLCandidateHarvester
- .SSL_CLIENT_HANDSHAKE))
- {
- socket.getOutputStream().write(
- GoogleTurnSSLCandidateHarvester
- .SSL_SERVER_HANDSHAKE);
- }
- else
- {
- throw new ReadThreadException(
- "Expected a pseudo ssl handshake, didn't get one.");
- }
- }
-
- // read an RFC4571 frame into datagramPacket
-
- // TODO refactor so that:
- // 1. We don't block
- // 2. We know the length of the buffer to allocate
- DatagramPacket datagramPacket
- = new DatagramPacket(new byte[1500],1500);
- DelegatingSocket.receiveFromNetwork(
- datagramPacket,
- inputStream,
- socket.getInetAddress(),
- socket.getPort());
-
- // Does this look like a STUN binding request?
- // What's the username?
- Message stunMessage
- = Message.decode(datagramPacket.getData(),
- (char) datagramPacket.getOffset(),
- (char) datagramPacket.getLength());
-
- if (stunMessage.getMessageType() != Message.BINDING_REQUEST)
- throw new ReadThreadException("Not a binding request");
-
- UsernameAttribute usernameAttribute
- = (UsernameAttribute)
- stunMessage.getAttribute(Attribute.USERNAME);
- if (usernameAttribute == null)
- throw new ReadThreadException(
- "No USERNAME attribute present.");
-
- String usernameString
- = new String(usernameAttribute.getUsername());
- String localUfrag = usernameString.split(":")[0];
- Component component = getComponent(localUfrag);
- if (component == null)
- throw new ReadThreadException("No component found.");
-
-
- //phew, finally
- handSocketToComponent(socket, component, datagramPacket);
- }
- catch (IOException e)
- {
- logger.info("Failed to read from socket: " + e);
- }
- catch (StunException e)
- {
- logger.info("Failed to read from socket: " + e);
- }
- catch (ReadThreadException e)
- {
- logger.info("Failed to read from socket: " + e);
- }
- finally
- {
- channels.remove(channel);
- }
- }
-
- /**
- * Makes socket available to component and pushes
- * back datagramPacket into the STUN socket.
- * @param socket the Socket.
- * @param component the Component.
- * @param datagramPacket the DatagramPacket to push back.
- */
- private void handSocketToComponent(Socket socket,
- Component component,
- DatagramPacket datagramPacket)
- {
- IceProcessingState state
- = component.getParentStream().getParentAgent().getState();
- if (!IceProcessingState.WAITING.equals(state)
- && !IceProcessingState.RUNNING.equals(state))
- {
- logger.info("Not adding a socket to an ICE agent with state "
- + state);
- return;
- }
-
- // Socket to add to the candidate
- IceSocketWrapper candidateSocket = null;
-
- // STUN-only filtered socket to add to the StunStack
- IceSocketWrapper stunSocket = null;
-
- try
- {
- MultiplexingSocket multiplexing = new MultiplexingSocket(socket);
- candidateSocket = new IceTcpSocketWrapper(multiplexing);
-
- stunSocket
- = new IceTcpSocketWrapper(
- multiplexing.getSocket(new StunDatagramPacketFilter()));
- stunSocket
- = new PushBackIceSocketWrapper(stunSocket, datagramPacket);
- }
- catch (IOException ioe)
- {
- logger.info("Failed to create sockets: " + ioe);
- }
-
- TcpHostCandidate candidate = findCandidate(component, socket);
- if (candidate != null)
- {
- component.getParentStream().getParentAgent()
- .getStunStack().addSocket(stunSocket);
- candidate.addSocket(candidateSocket);
-
- // the socket is not our responsibility anymore. It is up to
- // the candidate/component to close/free it.
- }
- else
- {
- logger.info("Failed to find the local candidate for socket: "
- + socket);
- try
- {
- socket.close();
- }
- catch (IOException ioe)
- {}
- }
-
- }
-
- /**
- * Searches among the local candidates of Component for a
- * TcpHostCandidate with the same transport address as the
- * local transport address of socket.
- *
- * We expect to find such a candidate, which has been added by this
- * MultiplexingTcpHostHarvester while harvesting.
- *
- * @param component the Component to search.
- * @param socket the Socket to match the local transport
- * address of.
- * @return a TcpHostCandidate among the local candidates of
- * Component with the same transport address as the local
- * address of Socket, or null if no such candidate
- * exists.
- */
- private TcpHostCandidate findCandidate(Component component, Socket socket)
- {
- InetAddress localAddress = socket.getLocalAddress();
- int localPort = socket.getLocalPort();
-
- for (LocalCandidate candidate : component.getLocalCandidates())
- {
- TransportAddress transportAddress
- = candidate.getTransportAddress();
- if (candidate instanceof TcpHostCandidate
- && Transport.TCP.equals(transportAddress.getTransport())
- && localPort == transportAddress.getPort()
- && localAddress.equals(transportAddress.getAddress()))
- {
- return (TcpHostCandidate) candidate;
- }
- }
- return null;
- }
-
- /**
- * Adds the channels from {@link #newChannels} to {@link #channels}
- * and registers them in {@link #selector}.
- */
- private void checkForNewChannels()
- {
- synchronized (newChannels)
- {
- for (SocketChannel channel : newChannels)
- {
- try
- {
- channel.configureBlocking(false);
- channel.register(selector, SelectionKey.OP_READ);
- }
- catch (IOException ioe)
- {
- logger.info("Failed to register channel: " + ioe);
- try
- {
- channel.close();
- }
- catch (IOException ioe2)
- {}
- }
-
- channels.put(channel, System.currentTimeMillis());
- }
- newChannels.clear();
- }
- }
}
-
- /**
- * An exception used internally by
- * {@link org.ice4j.ice.harvest.MultiplexingTcpHostHarvester.ReadThread}.
- */
- @SuppressWarnings("serial")
- private class ReadThreadException
- extends Exception
- {
- private ReadThreadException(String s)
- {
- super(s);
- }
- }
-
- /**
- * An IceSocketWrapper implementation which allows a
- * DatagramPacket to be pushed back and received on the first
- * call to {@link #receive(java.net.DatagramPacket)}
- */
- private static class PushBackIceSocketWrapper
- extends IceSocketWrapper
- {
- /**
- * The IceSocketWrapper that this instance wraps around.
- */
- private IceSocketWrapper wrapped;
-
- /**
- * The DatagramPacket which will be used on the first call
- * to {@link #receive(java.net.DatagramPacket)}.
- */
- private DatagramPacket datagramPacket;
-
- /**
- * Initializes a new PushBackIceSocketWrapper instance that
- * wraps around wrappedWrapper and reads from
- * datagramSocket on the first call to
- * {@link #receive(java.net.DatagramPacket)}
- *
- * @param wrappedWrapper the IceSocketWrapper instance that we
- * wrap around.
- * @param datagramPacket the DatagramPacket which will be used
- * on the first call to {@link #receive(java.net.DatagramPacket)}
- */
- private PushBackIceSocketWrapper(IceSocketWrapper wrappedWrapper,
- DatagramPacket datagramPacket)
- {
- this.wrapped = wrappedWrapper;
- this.datagramPacket = datagramPacket;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void send(DatagramPacket p) throws IOException
- {
- wrapped.send(p);
- }
-
- /**
- * {@inheritDoc}
- *
- * On the first call to this instance reads from {@link #datagramPacket},
- * on subsequent calls delegates to {@link #wrapped}.
- */
- @Override
- public void receive(DatagramPacket p) throws IOException
- {
- if (datagramPacket != null)
- {
- int len = Math.min(p.getLength(), datagramPacket.getLength());
- System.arraycopy(datagramPacket.getData(), 0,
- p.getData(), 0,
- len);
- p.setAddress(datagramPacket.getAddress());
- p.setPort(datagramPacket.getPort());
- datagramPacket = null;
- }
- else
- {
- wrapped.receive(p);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void close()
- {
- wrapped.close();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public InetAddress getLocalAddress()
- {
- return wrapped.getLocalAddress();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public int getLocalPort()
- {
- return wrapped.getLocalPort();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public SocketAddress getLocalSocketAddress()
- {
- return wrapped.getLocalSocketAddress();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Socket getTCPSocket()
- {
- return wrapped.getTCPSocket();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public DatagramSocket getUDPSocket()
- {
- return wrapped.getUDPSocket();
- }
- }
-
}
diff --git a/src/org/ice4j/socket/DelegatingSocket.java b/src/org/ice4j/socket/DelegatingSocket.java
index 29ded6c..806d811 100644
--- a/src/org/ice4j/socket/DelegatingSocket.java
+++ b/src/org/ice4j/socket/DelegatingSocket.java
@@ -7,9 +7,9 @@
package org.ice4j.socket;
import java.io.*;
+import java.net.*;
import java.nio.*;
import java.nio.channels.*;
-import java.net.*;
/**
* Implements a Socket which delegates its calls to a specific
@@ -20,6 +20,75 @@ import java.net.*;
public class DelegatingSocket
extends Socket
{
+ /**
+ * Receives an RFC4571-formatted frame from inputStream into
+ * p, and sets p's port and address to port and
+ * inetAddress.
+ *
+ * @param p the DatagramPacket into which to place the incoming
+ * data.
+ * @param inputStream The TCP stream to be read.
+ * @param inetAddress The receiver address (local address) to set to the
+ * datagram packet.
+ * @param port The receiver port (local port) to set to the datagram packet.
+ *
+ * @throws IOException if an I/O error occurs
+ * @see #receive(DatagramPacket)
+ */
+ public static void receiveFromNetwork(
+ DatagramPacket p,
+ InputStream inputStream,
+ InetAddress inetAddress,
+ int port)
+ throws IOException
+ {
+ byte data[] = p.getData();
+ int len = 0;
+
+ int fb = inputStream.read();
+ int sb = inputStream.read();
+
+ // If we do not achieve to read the first bytes, then it was just an
+ // hole punch packet.
+ if(fb == -1 || sb == -1)
+ {
+ p.setLength(0);
+ throw new SocketException("read failed");
+ }
+
+ int desiredLength = (((fb & 0xff) << 8) | (sb & 0xff));
+ int readLen = 0;
+ int offset = 0;
+
+ while(readLen < desiredLength)
+ {
+ len = inputStream.read(data, offset, desiredLength - offset);
+ if(len == -1)
+ throw new SocketException("read failed");
+ offset += len;
+ readLen += len;
+ }
+
+ if (readLen == desiredLength)
+ {
+ p.setData(data);
+ p.setLength(len);
+ p.setAddress(inetAddress);
+ p.setPort(port);
+ }
+ else
+ {
+ throw new SocketException("Failed to receive data from socket");
+ }
+ }
+
+ /**
+ * A ByteBuffer instance used in
+ * {@link #receiveFromChannel(java.nio.channels.SocketChannel, java.net.DatagramPacket)}
+ * to read the 2-byte length field into.
+ */
+ private final ByteBuffer byteBufferLen = ByteBuffer.allocate(2);
+
/**
* Delegate Socket.
*/
@@ -31,9 +100,19 @@ public class DelegatingSocket
private InputStream inputStream = null;
/**
- * OutputStream for this socket.
+ * The last time an information about packet lost has been logged.
*/
- private OutputStream outputStream = null;
+ private long lastLostPacketLogTime = 0;
+
+ /**
+ * The last RTP sequence number received for this socket.
+ */
+ private long lastRtpSequenceNumber = -1;
+
+ /**
+ * The number of RTP packets lost (not received) for this socket.
+ */
+ private long nbLostRtpPackets = 0;
/**
* The number of RTP packets received for this socket.
@@ -46,33 +125,16 @@ public class DelegatingSocket
private long nbSentRtpPackets = 0;
/**
- * The number of RTP packets lost (not received) for this socket.
+ * OutputStream for this socket.
*/
- private long nbLostRtpPackets = 0;
-
- /**
- * The last RTP sequence number received for this socket.
- */
- private long lastRtpSequenceNumber = -1;
-
- /**
- * The last time an information about packet lost has been logged.
- */
- private long lastLostPacketLogTime = 0;
-
- /**
- * A ByteBuffer instance used in
- * {@link #receiveFromChannel(java.nio.channels.SocketChannel, java.net.DatagramPacket)}
- * to read the 2-byte length field into.
- */
- private final ByteBuffer byteBufferLen = ByteBuffer.allocate(2);
+ private OutputStream outputStream = null;
/**
* Initializes a new DelegatingSocket.
*/
public DelegatingSocket()
{
- delegate = null;
+ this((Socket) null);
}
/**
@@ -83,7 +145,7 @@ public class DelegatingSocket
public DelegatingSocket(InetAddress address, int port)
throws IOException
{
- delegate = null;
+ this((Socket) null);
}
/**
@@ -91,11 +153,12 @@ public class DelegatingSocket
*
* @see Socket#Socket(InetAddress, int, InetAddress, int)
*/
- public DelegatingSocket(InetAddress address, int port,
- InetAddress localAddr, int localPort)
+ public DelegatingSocket(
+ InetAddress address, int port,
+ InetAddress localAddr, int localPort)
throws IOException
{
- delegate = null;
+ this((Socket) null);
}
/**
@@ -105,7 +168,17 @@ public class DelegatingSocket
*/
public DelegatingSocket(Proxy proxy)
{
- delegate = null;
+ this((Socket) null);
+ }
+
+ /**
+ * Initializes a new DelegatingSocket.
+ *
+ * @param delegate delegating socket
+ */
+ public DelegatingSocket(Socket delegate)
+ {
+ this.delegate = delegate;
}
/**
@@ -116,7 +189,7 @@ public class DelegatingSocket
protected DelegatingSocket(SocketImpl impl)
throws SocketException
{
- delegate = null;
+ this((Socket) null);
}
/**
@@ -125,10 +198,9 @@ public class DelegatingSocket
* @see Socket#Socket(String, int)
*/
public DelegatingSocket(String host, int port)
- throws UnknownHostException,
- IOException
+ throws UnknownHostException, IOException
{
- delegate = null;
+ this((Socket) null);
}
/**
@@ -136,21 +208,11 @@ public class DelegatingSocket
*
* @see Socket#Socket(String, int, InetAddress, int)
*/
- public DelegatingSocket(String host, int port, InetAddress localAddr,
- int localPort)
+ public DelegatingSocket(
+ String host, int port,
+ InetAddress localAddr, int localPort)
{
- delegate = null;
- }
-
- /**
- * Initializes a new DelegatingSocket.
- *
- * @param socket delegating socket
- */
- public DelegatingSocket(Socket socket)
- {
- super();
- this.delegate = socket;
+ this((Socket) null);
}
/**
@@ -558,6 +620,154 @@ public class DelegatingSocket
}
}
+ /**
+ * Receives a datagram packet from this socket. The DatagramPackets
+ * returned by this method do not match any of the
+ * DatagramPacketFilters of the MultiplexedSockets
+ * associated with this instance at the time of their receipt. 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.
+ *
+ * This method blocks until a datagram is received. The length
+ * field of the datagram packet object contains the length of the received
+ * message. If the message is longer than the packet's length, the message
+ * is truncated.
+ *
+ *
+ * @param p the DatagramPacket into which to place the incoming
+ * data
+ * @throws IOException if an I/O error occurs
+ * @see #receive(DatagramPacket)
+ */
+ public void receive(DatagramPacket p)
+ throws IOException
+ {
+ if (delegate != null && delegate instanceof DelegatingSocket)
+ {
+ ((DelegatingSocket) delegate).receive(p);
+ }
+ else
+ {
+ SocketChannel channel = getChannel();
+
+ if (channel == null)
+ {
+ // Read from our InputStream
+ if (inputStream == null)
+ inputStream = getInputStream();
+
+ DelegatingSocket.receiveFromNetwork(
+ p,
+ inputStream,
+ this.getInetAddress(),
+ this.getPort());
+ }
+ else
+ {
+ // For nio SocketChannel-s, the read() from the InputStream and
+ // the write() to the OutputStream both lock on the same object.
+ // So, read from the Channel directly in order to avoid
+ // preventing any writing threads from proceeding.
+ receiveFromChannel(channel, p);
+ }
+
+ // no exception packet is successfully received, log it.
+ // If this is not a STUN/TURN packet, then this is a RTP packet.
+ if (!StunDatagramPacketFilter.isStunPacket(p))
+ ++nbReceivedRtpPackets;
+
+ InetSocketAddress localAddress
+ = (InetSocketAddress) super.getLocalSocketAddress();
+
+ DelegatingDatagramSocket.logPacketToPcap(
+ p,
+ nbReceivedRtpPackets,
+ false,
+ localAddress.getAddress(),
+ localAddress.getPort());
+ // Log RTP losses if > 5%.
+ updateRtpLosses(p);
+ }
+ }
+
+ /**
+ * Receives an RFC4571-formatted frame from channel into
+ * p, and sets p's port and address to the remote port
+ * and address of this Socket.
+ */
+ private synchronized void receiveFromChannel(SocketChannel channel,
+ DatagramPacket p)
+ throws IOException
+ {
+ int ret;
+ while (byteBufferLen.hasRemaining())
+ {
+ ret = channel.read(byteBufferLen);
+ if (ret == -1)
+ throw new SocketException("Failed to receive data from socket.");
+ }
+
+ byteBufferLen.flip();
+ int fb = byteBufferLen.get();
+ int sb = byteBufferLen.get();
+ int frameLength = (((fb & 0xff) << 8) | (sb & 0xff));
+ byteBufferLen.flip();
+
+ byte[] data = p.getData();
+ if (data == null || data.length < frameLength)
+ data = new byte[frameLength];
+
+ ByteBuffer byteBuffer = ByteBuffer.wrap(data, 0, frameLength);
+
+ while (byteBuffer.hasRemaining())
+ {
+ ret = channel.read(byteBuffer);
+ if (ret == -1)
+ throw new SocketException("Failed to receive data from socket.");
+ }
+
+ p.setData(data);
+ p.setLength(frameLength);
+ p.setAddress(getInetAddress());
+ p.setPort(getPort());
+ }
+
+ /**
+ * Send a datagram packet from this socket.
+ *
+ * @param p DatagramPacket to sent
+ * @throws IOException if something goes wrong during send
+ */
+ public void send(DatagramPacket p) throws IOException
+ {
+ // The delegate socket will encapsulate the packet.
+ if (delegate != null && delegate instanceof DelegatingSocket)
+ {
+ ((DelegatingSocket) delegate).send(p);
+ return;
+ }
+
+ if (outputStream == null)
+ {
+ outputStream = getOutputStream();
+ }
+
+ // Else, sends the packet to the final socket (outputStream).
+ outputStream.write(p.getData(), p.getOffset(), p.getLength());
+
+ // no exception packet is successfully sent, log it.
+ ++nbSentRtpPackets;
+ InetSocketAddress localAddress
+ = (InetSocketAddress) super.getLocalSocketAddress();
+ DelegatingDatagramSocket.logPacketToPcap(
+ p,
+ this.nbSentRtpPackets,
+ true,
+ localAddress.getAddress(),
+ localAddress.getPort());
+ }
+
/**
* {@inheritDoc}
*/
@@ -603,6 +813,17 @@ public class DelegatingSocket
}
}
+ /**
+ * Set original InputStream.
+ *
+ * @param inputStream InputStream
+ */
+ public void setOriginalInputStream(InputStream inputStream)
+ {
+ if(this.inputStream == null && inputStream != null)
+ this.inputStream = inputStream;
+ }
+
/**
* {@inheritDoc}
*/
@@ -770,228 +991,6 @@ public class DelegatingSocket
}
}
- /**
- * Send a datagram packet from this socket.
- *
- * @param p DatagramPacket to sent
- * @throws IOException if something goes wrong during send
- */
- public void send(DatagramPacket p) throws IOException
- {
- // The delegate socket will encapsulate the packet.
- if (delegate != null && delegate instanceof DelegatingSocket)
- {
- ((DelegatingSocket) delegate).send(p);
- return;
- }
-
- if (outputStream == null)
- {
- outputStream = getOutputStream();
- }
-
- // Else, sends the packet to the final socket (outputStream).
- outputStream.write(p.getData(), p.getOffset(), p.getLength());
-
- // no exception packet is successfully sent, log it.
- ++nbSentRtpPackets;
- InetSocketAddress localAddress
- = (InetSocketAddress) super.getLocalSocketAddress();
- DelegatingDatagramSocket.logPacketToPcap(
- p,
- this.nbSentRtpPackets,
- true,
- localAddress.getAddress(),
- localAddress.getPort());
- }
-
- /**
- * Receives a datagram packet from this socket. The DatagramPackets
- * returned by this method do not match any of the
- * DatagramPacketFilters of the MultiplexedSockets
- * associated with this instance at the time of their receipt. 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.
- *
- * This method blocks until a datagram is received. The length
- * field of the datagram packet object contains the length of the received
- * message. If the message is longer than the packet's length, the message
- * is truncated.
- *
- *
- * @param p the DatagramPacket into which to place the incoming
- * data
- * @throws IOException if an I/O error occurs
- * @see #receive(DatagramPacket)
- */
- public void receive(DatagramPacket p)
- throws IOException
- {
- if (delegate != null && delegate instanceof DelegatingSocket)
- {
- ((DelegatingSocket) delegate).receive(p);
- }
- else
- {
- SocketChannel channel = getChannel();
- if (channel == null)
- {
- // Read from our InputStream
- if (inputStream == null)
- {
- inputStream = this.getInputStream();
- }
-
- DelegatingSocket.receiveFromNetwork(
- p,
- inputStream,
- this.getInetAddress(),
- this.getPort());
- }
- else
- {
- // For nio SocketChannel-s, the read() from the InputStream and
- // the write() to the OutputStream both lock on the same object.
- // So, read from the Channel directly in order to avoid
- // preventing any writing threads from proceeding.
- receiveFromChannel(channel, p);
- }
-
- // no exception packet is successfully received, log it.
- // If this is not a STUN/TURN packet, then this is a RTP packet.
- if (!StunDatagramPacketFilter.isStunPacket(p))
- {
- ++nbReceivedRtpPackets;
- }
- InetSocketAddress localAddress
- = (InetSocketAddress) super.getLocalSocketAddress();
- DelegatingDatagramSocket.logPacketToPcap(
- p,
- this.nbReceivedRtpPackets,
- false,
- localAddress.getAddress(),
- localAddress.getPort());
- // Log RTP losses if > 5%.
- updateRtpLosses(p);
- }
- }
-
- /**
- * Receives an RFC4571-formatted frame from inputStream into
- * p, and sets p's port and address to port and
- * inetAddress.
- *
- * @param p the DatagramPacket into which to place the incoming
- * data.
- * @param inputStream The TCP stream to be read.
- * @param inetAddress The receiver address (local address) to set to the
- * datagram packet.
- * @param port The receiver port (local port) to set to the datagram packet.
- *
- * @throws IOException if an I/O error occurs
- * @see #receive(DatagramPacket)
- */
- public static void receiveFromNetwork(
- DatagramPacket p,
- InputStream inputStream,
- InetAddress inetAddress,
- int port)
- throws IOException
- {
- byte data[] = p.getData();
- int len = 0;
-
- int fb = inputStream.read();
- int sb = inputStream.read();
-
- // If we do not achieve to read the first bytes, then it was just an
- // hole punch packet.
- if(fb == -1 || sb == -1)
- {
- p.setLength(0);
- throw new SocketException("read failed");
- }
-
- int desiredLength = (((fb & 0xff) << 8) | (sb & 0xff));
- int readLen = 0;
- int offset = 0;
-
- while(readLen < desiredLength)
- {
- len = inputStream.read(data, offset, desiredLength - offset);
- if(len == -1)
- throw new SocketException("read failed");
- offset += len;
- readLen += len;
- }
-
- if (readLen == desiredLength)
- {
- p.setData(data);
- p.setLength(len);
- p.setAddress(inetAddress);
- p.setPort(port);
- }
- else
- {
- throw new SocketException("Failed to receive data from socket");
- }
- }
-
- /**
- * Receives an RFC4571-formatted frame from channel into
- * p, and sets p's port and address to the remote port
- * and address of this Socket.
- */
- private synchronized void receiveFromChannel(SocketChannel channel,
- DatagramPacket p)
- throws IOException
- {
- int ret;
- while (byteBufferLen.hasRemaining())
- {
- ret = channel.read(byteBufferLen);
- if (ret == -1)
- throw new SocketException("Failed to receive data from socket.");
- }
-
- byteBufferLen.flip();
- int fb = byteBufferLen.get();
- int sb = byteBufferLen.get();
- int frameLength = (((fb & 0xff) << 8) | (sb & 0xff));
- byteBufferLen.flip();
-
- byte[] data = p.getData();
- if (data == null || data.length < frameLength)
- data = new byte[frameLength];
-
- ByteBuffer byteBuffer = ByteBuffer.wrap(data, 0, frameLength);
-
- while (byteBuffer.hasRemaining())
- {
- ret = channel.read(byteBuffer);
- if (ret == -1)
- throw new SocketException("Failed to receive data from socket.");
- }
-
- p.setData(data);
- p.setLength(frameLength);
- p.setAddress(getInetAddress());
- p.setPort(getPort());
- }
-
- /**
- * Set original InputStream.
- *
- * @param inputStream InputStream
- */
- public void setOriginalInputStream(InputStream inputStream)
- {
- if(this.inputStream == null && inputStream != null)
- this.inputStream = inputStream;
- }
-
/**
* Updates and Logs information about RTP losses if there is more then 5% of
* RTP packet lost (at most every 5 seconds).
diff --git a/src/org/ice4j/socket/MultiplexedSocket.java b/src/org/ice4j/socket/MultiplexedSocket.java
index 4ed2751..dda3577 100644
--- a/src/org/ice4j/socket/MultiplexedSocket.java
+++ b/src/org/ice4j/socket/MultiplexedSocket.java
@@ -15,10 +15,9 @@ import java.util.logging.*;
/**
* Represents a Socket which receives DatagramPackets
* selected by a DatagramPacketFilter from a
- * MultiplexingSocket. The associated
- * MultiplexingSocket is the actual Socket
- * which reads the DatagramPackets from the network. The
- * DatagramPackets received through the
+ * MultiplexingSocket. The associated MultiplexingSocket is
+ * the actual Socket which reads the DatagramPackets from the
+ * network. The DatagramPackets received through the
* MultiplexedSocket will not be received through the
* associated MultiplexingSocket.
*
@@ -28,11 +27,12 @@ public class MultiplexedSocket
extends DelegatingSocket
{
/**
- * The Logger used by the MultiplexedSocket class
- * and its instances for logging output.
+ * The Logger used by the MultiplexedSocket class and its
+ * instances for logging output.
*/
private static final Logger logger
- = Logger.getLogger(MultiplexedSocket.class.getName());
+ = Logger.getLogger(MultiplexedSocket.class.getName());
+
/**
* The DatagramPacketFilter which determines which
* DatagramPackets read from the network by {@link #multiplexing}
@@ -41,8 +41,13 @@ public class MultiplexedSocket
private final DatagramPacketFilter filter;
/**
- * The MultiplexingSocket which does the actual reading
- * from the network and which forwards DatagramPackets accepted by
+ * The custom InputStream for this MultiplexedSocket.
+ */
+ private final InputStream inputStream = new InputStreamImpl();
+
+ /**
+ * The MultiplexingSocket which does the actual reading from the
+ * network and which forwards DatagramPackets accepted by
* {@link #filter} for receipt to this instance.
*/
private final MultiplexingSocket multiplexing;
@@ -54,20 +59,13 @@ public class MultiplexedSocket
final List received = new LinkedList();
/**
- * The custom InputStream for this MultiplexedSocket.
- */
- private final InputStreamImpl inputStream = new InputStreamImpl();
-
- /**
- * Initializes a new MultiplexedSocket which is unbound and
- * filters DatagramPackets away from a specific
- * MultiplexingSocket using a specific
- * DatagramPacketFilter.
+ * Initializes a new MultiplexedSocket which is unbound and filters
+ * DatagramPackets away from a specific MultiplexingSocket
+ * using a specific DatagramPacketFilter.
*
- * @param multiplexing the MultiplexingSocket which does
- * the actual reading from the network and which forwards
- * DatagramPackets accepted by the specified filter to the
- * new instance
+ * @param multiplexing the MultiplexingSocket which does the actual
+ * reading from the network and which forwards DatagramPackets
+ * accepted by the specified filter to the new instance
* @param filter the DatagramPacketFilter which determines which
* DatagramPackets read from the network by the specified
* multiplexing are to be received through the new instance
@@ -79,11 +77,11 @@ public class MultiplexedSocket
throws SocketException
{
/*
- * Even if MultiplexingSocket allows MultiplexedSocket
- * to perform bind, binding in the super will not execute correctly this
- * early in the construction because the multiplexing field is not set
- * yet. That is why MultiplexedSocket does not currently support
- * bind at construction time.
+ * Even if MultiplexingSocket allows MultiplexedSocket to perform bind,
+ * binding in the super will not execute correctly this early in the
+ * construction because the multiplexing field is not set yet. That is
+ * why MultiplexedSocket does not currently support bind at construction
+ * time.
*/
super(multiplexing);
@@ -109,15 +107,6 @@ public class MultiplexedSocket
multiplexing.close(this);
}
- /**
- * {@inheritDoc}
- */
- @Override
- public InputStream getInputStream()
- {
- return inputStream;
- }
-
/**
* Gets the DatagramPacketFilter which determines which
* DatagramPackets read from the network are to be received through
@@ -132,6 +121,15 @@ public class MultiplexedSocket
return filter;
}
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public InputStream getInputStream()
+ {
+ return inputStream;
+ }
+
/**
* Receives a datagram packet from this socket. When this method returns,
* the DatagramPacket's buffer is filled with the data received.
@@ -198,12 +196,23 @@ public class MultiplexedSocket
return false;
}
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int read()
+ throws IOException
+ {
+ // We don't support reading a single byte
+ return 0;
+ }
+
/**
* {@inheritDoc}
*/
@Override
public int read(byte[] b)
- throws IOException
+ throws IOException
{
return read(b, 0, b.length);
}
@@ -221,13 +230,19 @@ public class MultiplexedSocket
receive(packet);
int lengthRead = packet.getLength();
+
if (packet.getData() == b && lengthRead <= len)
+ {
return lengthRead;
+ }
else
- logger.warning("Failed to read directly into the provided"
- + " buffer, len=" + len + " lengthRead="
- + lengthRead + " (packet.getData() == b)="
- + (packet.getData() == b));
+ {
+ logger.warning(
+ "Failed to read directly into the provided buffer,"
+ + " len=" + len + " lengthRead=" + lengthRead
+ + " (packet.getData() == b)="
+ + (packet.getData() == b));
+ }
}
// either there's an offset to take into account, or receiving
@@ -238,6 +253,7 @@ public class MultiplexedSocket
int packetLen = packet.getLength();
int lengthRead = Math.min(len, packetLen);
+
System.arraycopy(
packet.getData(), packet.getOffset(),
b, off,
@@ -251,11 +267,12 @@ public class MultiplexedSocket
*/
@Override
public void reset()
- throws IOException
+ throws IOException
{
if(!markSupported())
{
- throw new IOException("InputStreamImpl does not support reset()");
+ throw new IOException(
+ "InputStreamImpl does not support reset()");
}
}
@@ -268,16 +285,5 @@ public class MultiplexedSocket
{
throw new IOException("InputStreamImpl does not support skip.");
}
-
- /**
- * {@inheritDoc}
- */
- @Override
- public int read()
- throws IOException
- {
- //We don't support reading a single byte
- return 0;
- }
}
}
diff --git a/src/org/ice4j/socket/MultiplexingDatagramSocket.java b/src/org/ice4j/socket/MultiplexingDatagramSocket.java
index b84bfbf..dce053a 100644
--- a/src/org/ice4j/socket/MultiplexingDatagramSocket.java
+++ b/src/org/ice4j/socket/MultiplexingDatagramSocket.java
@@ -8,6 +8,7 @@
package org.ice4j.socket;
import java.io.*;
+import java.lang.reflect.*;
import java.net.*;
import java.util.*;
import java.util.logging.*;
@@ -39,6 +40,24 @@ public class MultiplexingDatagramSocket
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
@@ -255,7 +274,6 @@ public class MultiplexingDatagramSocket
public MultiplexingDatagramSocket()
throws SocketException
{
- super();
}
/**
@@ -419,10 +437,8 @@ public class MultiplexingDatagramSocket
synchronized (socketsSyncRoot)
{
- /*
- * If a socket for the specified filter exists already, do not
- * create a new one and return the existing.
- */
+ // 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()))
@@ -437,21 +453,7 @@ public class MultiplexingDatagramSocket
= new MultiplexedDatagramSocket(this, filter);
// Remember the new socket.
- int socketCount = sockets.length;
-
- if (socketCount == 0)
- {
- sockets = new MultiplexedDatagramSocket[] { socket };
- }
- else
- {
- MultiplexedDatagramSocket[] newSockets
- = new MultiplexedDatagramSocket[socketCount + 1];
-
- System.arraycopy(sockets, 0, newSockets, 0, socketCount);
- newSockets[socketCount] = socket;
- sockets = newSockets;
- }
+ sockets = add(sockets, socket);
return socket;
}
diff --git a/src/org/ice4j/socket/MultiplexingSocket.java b/src/org/ice4j/socket/MultiplexingSocket.java
index 8822bd9..93121cf 100644
--- a/src/org/ice4j/socket/MultiplexingSocket.java
+++ b/src/org/ice4j/socket/MultiplexingSocket.java
@@ -13,10 +13,10 @@ import java.util.*;
import java.util.logging.*;
/**
- * Represents a Socket which allows filtering
- * DatagramPackets it reads from the network using
- * DatagramPacketFilters so that the DatagramPackets do not
- * get received through it but through associated MultiplexedSockets.
+ * Represents a Socket which allows filtering DatagramPackets
+ * it reads from the network using DatagramPacketFilters so that the
+ * DatagramPackets do not get received through it but through
+ * associated MultiplexedSockets.
*
* @author Sebastien Vincent
* @author Lyubomir Marinov
@@ -25,55 +25,54 @@ public class MultiplexingSocket
extends DelegatingSocket
{
/**
- * The Logger used by the MultiplexingSocket class
- * and its instances for logging output.
+ * The Logger used by the MultiplexingSocket class and its
+ * instances for logging output.
*/
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.
+ * MultiplexedSocket element type. Explicitly defined in order to
+ * reduce allocations.
*/
private static final MultiplexedSocket[] NO_SOCKETS
= new MultiplexedSocket[0];
- /**
- * 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.
- */
- private boolean inReceive = false;
-
- /**
- * The list of DatagramPackets to be received through this
- * Socket i.e. not accepted by the DatagramFilters
- * of {@link #sockets} at the time of the reading from the network.
- */
- private final List received
- = new LinkedList();
-
/**
* Custom InputStream for this Socket.
*/
- private final TCPInputStream inputStream = new TCPInputStream();
+ 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.
+ */
+ private boolean inReceive = false;
/**
* Custom OutputStream for this Socket.
*/
private TCPOutputStream outputStream = null;
+ /**
+ * The list of DatagramPackets to be received through this
+ * Socket i.e. not accepted by the DatagramFilters of
+ * {@link #sockets} at the time of the reading from the network.
+ */
+ private final List received
+ = new LinkedList();
+
/**
* The Object which synchronizes the access to {@link #inReceive}.
*/
private final Object receiveSyncRoot = new Object();
/**
- * The MultiplexedSockets filtering DatagramPackets
- * away from this Socket.
+ * The MultiplexedSockets filtering DatagramPackets away
+ * from this Socket.
*/
private MultiplexedSocket[] sockets = NO_SOCKETS;
@@ -84,11 +83,11 @@ public class MultiplexingSocket
private final Object socketsSyncRoot = new Object();
/**
- * Buffer variable for storing the SO_TIMEOUT value set by the
- * last setSoTimeout() call. Altough not strictly needed,
- * getting the locally stored value as opposed to retrieving it
- * from a parent getSoTimeout() call seems to
- * significantly improve efficiency, at least on some platforms.
+ * Buffer variable for storing the SO_TIMEOUT value set by the last
+ * setSoTimeout() call. Although not strictly needed, getting the
+ * locally stored value as opposed to retrieving it from a parent
+ * getSoTimeout() call seems to significantly improve efficiency,
+ * at least on some platforms.
*/
private int soTimeout = 0;
@@ -99,15 +98,7 @@ public class MultiplexingSocket
*/
public MultiplexingSocket()
{
- super();
- try
- {
- setTcpNoDelay(true);
- }
- catch(SocketException e)
- {
- logger.info("Cannot SO_TCPNODELAY");
- }
+ this((Socket) null);
}
/**
@@ -118,15 +109,7 @@ public class MultiplexingSocket
public MultiplexingSocket(InetAddress address, int port)
throws IOException
{
- super(address, port);
- try
- {
- setTcpNoDelay(true);
- }
- catch(SocketException e)
- {
- logger.info("Cannot SO_TCPNODELAY");
- }
+ this((Socket) null);
}
/**
@@ -134,19 +117,12 @@ public class MultiplexingSocket
*
* @see Socket#Socket(InetAddress, int, InetAddress, int)
*/
- public MultiplexingSocket(InetAddress address, int port,
- InetAddress localAddr, int localPort)
+ public MultiplexingSocket(
+ InetAddress address, int port,
+ InetAddress localAddr, int localPort)
throws IOException
{
- super(address, port, localAddr, localPort);
- try
- {
- setTcpNoDelay(true);
- }
- catch(SocketException e)
- {
- logger.info("Cannot SO_TCPNODELAY");
- }
+ this((Socket) null);
}
/**
@@ -156,12 +132,23 @@ public class MultiplexingSocket
*/
public MultiplexingSocket(Proxy proxy)
{
- super(proxy);
+ this((Socket) null);
+ }
+
+ /**
+ * Initializes a new MultiplexingSocket instance.
+ *
+ * @param socket delegate socket
+ */
+ public MultiplexingSocket(Socket socket)
+ {
+ super(socket);
+
try
{
setTcpNoDelay(true);
}
- catch(SocketException e)
+ catch (SocketException ex)
{
logger.info("Cannot SO_TCPNODELAY");
}
@@ -175,15 +162,7 @@ public class MultiplexingSocket
protected MultiplexingSocket(SocketImpl impl)
throws SocketException
{
- super(impl);
- try
- {
- setTcpNoDelay(true);
- }
- catch(SocketException e)
- {
- logger.info("Cannot SO_TCPNODELAY");
- }
+ this((Socket) null);
}
/**
@@ -192,18 +171,9 @@ public class MultiplexingSocket
* @see Socket#Socket(String, int)
*/
public MultiplexingSocket(String host, int port)
- throws UnknownHostException,
- IOException
+ throws UnknownHostException, IOException
{
- super(host, port);
- try
- {
- setTcpNoDelay(true);
- }
- catch(SocketException e)
- {
- logger.info("Cannot SO_TCPNODELAY");
- }
+ this((Socket) null);
}
/**
@@ -211,217 +181,11 @@ public class MultiplexingSocket
*
* @see Socket#Socket(String, int, InetAddress, int)
*/
- public MultiplexingSocket(String host, int port,
- InetAddress localAddr, int localPort)
+ public MultiplexingSocket(
+ String host, int port,
+ InetAddress localAddr, int localPort)
{
- super(host, port, localAddr, localPort);
- try
- {
- setTcpNoDelay(true);
- }
- catch(SocketException e)
- {
- logger.info("Cannot SO_TCPNODELAY");
- }
- }
-
- /**
- * Initializes a new MultiplexingSocket instance.
- *
- * @param socket delegate socket
- */
- public MultiplexingSocket(Socket socket)
- {
- super(socket);
- try
- {
- setTcpNoDelay(true);
- }
- catch(SocketException e)
- {
- logger.info("Cannot SO_TCPNODELAY");
- }
- }
-
- /**
- * Receives a datagram packet from this socket. The DatagramPackets
- * returned by this method do not match any of the
- * DatagramPacketFilters of the MultiplexedDatagramSockets
- * associated with this instance at the time of their receipt. 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.
- *
- * This method blocks until a datagram is received. The length
- * field of the datagram packet object contains the length of the received
- * message. If the message is longer than the packet's length, the message
- * is truncated.
- *
- *
- * @param p the DatagramPacket into which to place the incoming
- * data
- * @throws IOException if an I/O error occurs
- * @see DelegatingSocket#receive(DatagramPacket)
- */
- @Override
- public void receive(DatagramPacket p)
- throws SocketTimeoutException, IOException
- {
- try
- {
- setOriginalInputStream(super.getInputStream());
- }
- catch(Exception e)
- {
- }
- receive(received, p, soTimeout);
- }
-
- /**
- * Receives a DatagramPacket from this Socket upon
- * request from a specific MultiplexedSocket.
- *
- * @param multiplexed the MultiplexedSocket which requests
- * the receipt of a DatagramPacket from the network
- * @param p the DatagramPacket to receive the data from the network
- * @throws IOException if an I/O error occurs
- */
- void receive(MultiplexedSocket multiplexed, DatagramPacket p)
- throws SocketTimeoutException, IOException
- {
- try
- {
- setOriginalInputStream(super.getInputStream());
- }
- catch(Exception e)
- {
- }
- receive(multiplexed.received, p, multiplexed.getSoTimeout());
- }
-
- /**
- * 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 SocketTimeoutException, IOException
- {
- long now, start = System.currentTimeMillis();
- DatagramPacket r = null;
-
- do
- {
- now = System.currentTimeMillis();
- if (timeout > 0 && now - start >= timeout)
- throw new SocketTimeoutException("Socket timeout");
-
- boolean doReceive;
-
- synchronized (receiveSyncRoot)
- {
- if (received.isEmpty())
- {
- if (inReceive)
- {
- doReceive = false;
- try
- {
- if (timeout > 0)
- receiveSyncRoot.wait(timeout - (now - start));
- else
- receiveSyncRoot.wait();
- }
- catch (InterruptedException iex)
- {
- continue;
- }
- }
- else
- {
- doReceive = true;
- inReceive = true;
- }
- }
- else
- {
- doReceive = false;
- r = received.remove(0);
- }
- }
- if (doReceive)
- {
- try
- {
- super.receive(p);
-
- synchronized (receiveSyncRoot)
- {
- synchronized (socketsSyncRoot)
- {
- boolean accepted = false;
-
- for (MultiplexedSocket socket : sockets)
- if (socket.getFilter().accept(p))
- {
- socket.received.add(
- MultiplexingDatagramSocket.clone(p));
- accepted = true;
-
- /*
- * Emil: Don't break because we want all
- * filtering sockets to get this.
- */
- //break;
- }
-
- if (!accepted)
- addReceivedPacket(p);
- }
- }
- }
- finally
- {
- synchronized (receiveSyncRoot)
- {
- inReceive = false;
- receiveSyncRoot.notify();
- }
- }
- }
- }
- while (r == null);
-
- MultiplexingDatagramSocket.copy(r, p);
- }
-
- /**
- * Close socket.
- */
- public void close()
- {
- try
- {
- super.close();
- }
- catch(IOException e)
- {
- }
+ this((Socket) null);
}
/**
@@ -441,7 +205,9 @@ public class MultiplexingSocket
if (sockets[i].equals(multiplexed))
{
if (socketCount == 1)
+ {
sockets = NO_SOCKETS;
+ }
else
{
MultiplexedSocket[] newSockets
@@ -460,99 +226,16 @@ public class MultiplexingSocket
}
}
- /**
- * 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 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.
- int socketCount = sockets.length;
-
- if (socketCount == 0)
- sockets = new MultiplexedSocket[] { socket };
- else
- {
- MultiplexedSocket[] newSockets
- = new MultiplexedSocket[socketCount + 1];
-
- System.arraycopy(sockets, 0, newSockets, 0, socketCount);
- newSockets[socketCount] = socket;
- sockets = newSockets;
- }
-
- return socket;
- }
- }
-
- /**
- * Add received packet.
- *
- * @param p DatagramPacket
- */
- public void addReceivedPacket(DatagramPacket p)
- {
- byte data[] = p.getData();
- int len = p.getLength();
- byte newData[] = new byte[len];
-
- System.arraycopy(data, p.getOffset(), newData, 0, len);
- inputStream.addPacket(newData);
- }
-
/**
* {@inheritDoc}
*/
+ @Override
public InputStream getInputStream()
throws IOException
{
return inputStream;
}
- /**
- * {@inheritDoc}
- */
- public OutputStream getOutputStream()
- throws IOException
- {
- if(outputStream == null)
- {
- outputStream = new TCPOutputStream(super.getOutputStream());
- }
-
- return outputStream;
- }
-
/**
* Get original InputStream.
*
@@ -581,11 +264,54 @@ public class MultiplexingSocket
* {@inheritDoc}
*/
@Override
- public void setSoTimeout(int timeout)
- throws SocketException
+ public OutputStream getOutputStream()
+ throws IOException
{
- super.setSoTimeout(timeout);
- soTimeout = timeout;
+ if (outputStream == null)
+ outputStream = new TCPOutputStream(super.getOutputStream());
+ return outputStream;
+ }
+
+ /**
+ * 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 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;
+ }
}
/**
@@ -597,4 +323,232 @@ public class MultiplexingSocket
return soTimeout;
}
+ /**
+ * Receives a datagram packet from this socket. The DatagramPackets
+ * returned by this method do not match any of the
+ * DatagramPacketFilters of the MultiplexedDatagramSockets
+ * associated with this instance at the time of their receipt. 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.
+ *
+ * This method blocks until a datagram is received. The length
+ * field of the datagram packet object contains the length of the received
+ * message. If the message is longer than the packet's length, the message
+ * is truncated.
+ *
+ *
+ * @param p the DatagramPacket into which to place the incoming
+ * data
+ * @throws IOException if an I/O error occurs
+ * @see DelegatingSocket#receive(DatagramPacket)
+ */
+ @Override
+ public void receive(DatagramPacket p)
+ throws IOException
+ {
+ try
+ {
+ setOriginalInputStream(super.getInputStream());
+ }
+ 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: 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);
+ }
+
+ /**
+ * Receives a DatagramPacket from this Socket upon
+ * request from a specific MultiplexedSocket.
+ *
+ * @param multiplexed the MultiplexedSocket which requests
+ * the receipt of a DatagramPacket from the network
+ * @param p the DatagramPacket to receive the data from the network
+ * @throws IOException if an I/O error occurs
+ */
+ void receive(MultiplexedSocket multiplexed, DatagramPacket p)
+ throws IOException
+ {
+ try
+ {
+ setOriginalInputStream(super.getInputStream());
+ }
+ catch(Exception e)
+ {
+ }
+ receive(multiplexed.received, p, multiplexed.getSoTimeout());
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void setSoTimeout(int timeout)
+ throws SocketException
+ {
+ super.setSoTimeout(timeout);
+
+ soTimeout = timeout;
+ }
}
diff --git a/src/org/ice4j/socket/TCPInputStream.java b/src/org/ice4j/socket/TCPInputStream.java
index 5f81c13..36965ed 100644
--- a/src/org/ice4j/socket/TCPInputStream.java
+++ b/src/org/ice4j/socket/TCPInputStream.java
@@ -8,56 +8,81 @@
package org.ice4j.socket;
import java.io.*;
-import java.util.*;
+import java.net.*;
/**
- * TCP input stream for TCP socket. It is used to multiplex sockets and keep
- * the InputStream interface to users.
+ * TCP input stream for TCP socket. It is used to multiplex sockets and keep the
+ * InputStream interface to users.
*
* @author Sebastien Vincent
+ * @author Lyubomir Marinov
*/
public class TCPInputStream
extends InputStream
{
/**
- * List of packets.
+ * The default size of the receive buffer of TCPInputStream if the
+ * associated MultiplexingSocket does not specify a value.
*/
- private final List packets = new ArrayList();
+ private static final int DEFAULT_RECEIVE_BUFFER_SIZE = 65536;
+
+ /**
+ * The byte array with one element which is used by the
+ * implementation of {@link #read()} in order to delegate to the
+ * implementation of {@link #read(byte[], int, int)} for the purposes of
+ * simplicity.
+ */
+ private final byte[] b = new byte[1];
+
+ /**
+ * The indicator which determines whether this TCPInputStream is
+ * executing one of its read method implementations.
+ */
+ private boolean inRead;
/**
* Current packet being processed if any.
*/
- private byte[] currentPacket = null;
+ private DatagramPacket packet;
/**
- * Current offset.
+ * The data of {@link #packet}.
*/
- private int currentPacketOffset = 0;
+ private byte[] packetData;
/**
* Current packet length.
*/
- private int currentPacketLength = 0;
+ private int packetLength;
/**
- * Synchronization object for read operation.
+ * Current offset.
+ */
+ private int packetOffset;
+
+ /**
+ * The Object which synchronizes the access to the read-related
+ * state of this instance.
*/
private final Object readSyncRoot = new Object();
/**
- * Initializes a new TCPInputStream.
+ * The MultiplexingSocket which has initialized this instance and
+ * is using it as its inputStream.
*/
- public TCPInputStream()
- {
- }
+ private final MultiplexingSocket socket;
/**
- * {@inheritDoc}
+ * Initializes a new TCPInputStream.
+ *
+ * @param socket
*/
- @Override
- public int available()
+ public TCPInputStream(MultiplexingSocket socket)
{
- return 0;
+ if (socket == null)
+ throw new NullPointerException("socket");
+
+ this.socket = socket;
}
/**
@@ -67,111 +92,8 @@ public class TCPInputStream
public void close()
throws IOException
{
- packets.clear();
- currentPacket = null;
- currentPacketOffset = 0;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void mark(int readLimit)
- {
- /* do nothing */
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean markSupported()
- {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public int read(byte[] b)
- {
- return read(b, 0, b.length);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public int read(byte[] b, int off, int len)
- {
- synchronized(readSyncRoot)
- {
- getNextPacket();
-
- int length = currentPacketLength;
-
- if(len < length)
- {
- length = len;
- }
-
- System.arraycopy(currentPacket, currentPacketOffset, b, off,
- length);
-
- currentPacketOffset += length;
- currentPacketLength -= length;
-
- if(currentPacketLength <= 0)
- {
- currentPacket = null;
- currentPacketOffset = 0;
- currentPacketLength = 0;
- }
- return length;
- }
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void reset()
- throws IOException
- {
- if(!markSupported())
- {
- throw new IOException("TCPInputStream does not support reset()");
- }
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public long skip(long n)
- throws IOException
- {
- synchronized(readSyncRoot)
- {
- getNextPacket();
-
- if(n > currentPacketLength)
- {
- n = currentPacketLength;
- }
- currentPacketOffset += n;
- currentPacketLength -= n;
-
- if(currentPacketLength <= 0)
- {
- currentPacket = null;
- currentPacketOffset = 0;
- currentPacketLength = 0;
- }
-
- return n;
- }
+ // TODO Auto-generated method stub
+ super.close();
}
/**
@@ -181,56 +103,151 @@ public class TCPInputStream
public int read()
throws IOException
{
- getNextPacket();
- int ret = currentPacket[currentPacketOffset];
- currentPacketOffset++;
- currentPacketLength--;
+ synchronized (readSyncRoot)
+ {
+ waitWhileInRead();
+ inRead = true;
+ }
+ try
+ {
+ do
+ {
+ int read = read0(b, 0, 1);
- return ret;
+ if (read == -1)
+ return read;
+ if (read == 1)
+ return b[0];
+ }
+ while (true);
+ }
+ finally
+ {
+ synchronized (readSyncRoot)
+ {
+ inRead = false;
+ }
+ }
}
/**
- * Get next packet. It blocks if no packets are available.
- *
- * @return next packet
+ * {@inheritDoc}
*/
- private byte[] getNextPacket()
+ @Override
+ public int read(byte[] b, int off, int len)
+ throws IOException
{
- synchronized(packets)
+ int read;
+
+ // The javadoc on InputStream.read(byte[], int, int) says that, if len
+ // is zero, no bytes are read and zero is returned.
+ if (len == 0)
{
- if(packets.size() == 0)
+ read = 0;
+ }
+ else
+ {
+ synchronized (readSyncRoot)
+ {
+ waitWhileInRead();
+ inRead = true;
+ }
+ try
+ {
+ read = read0(b, off, len);
+ }
+ finally
+ {
+ synchronized (readSyncRoot)
+ {
+ inRead = false;
+ }
+ }
+ }
+ return read;
+ }
+
+ protected int read0(byte[] b, int off, int len)
+ throws IOException
+ {
+ int read;
+
+ do
+ {
+ if (packetLength > 0)
+ {
+ // Data has already been received from the network.
+ read = Math.min(packetLength, len);
+ System.arraycopy(packetData, packetOffset, b, off, read);
+ packetLength -= read;
+ packetOffset += read;
+ break;
+ }
+
+ // Receive from the network.
+
+ // Make sure that the receive buffer of this InputStream satisfies
+ // the requirements with respect to size of the socket.
+ int receiveBufferSize = socket.getReceiveBufferSize();
+
+ if (receiveBufferSize < 1)
+ receiveBufferSize = DEFAULT_RECEIVE_BUFFER_SIZE;
+ if ((packetData == null) || (packetData.length < receiveBufferSize))
+ packetData = new byte[receiveBufferSize];
+ if (packet == null)
+ packet = new DatagramPacket(packetData, 0, packetData.length);
+ else
+ packet.setData(packetData, 0, packetData.length);
+ packetLength = 0;
+ packetOffset = 0;
+
+ socket.receive(packet);
+
+ packetData = packet.getData();
+ packetLength = packet.getLength();
+ packetOffset = packet.getOffset();
+ }
+ while (true);
+
+ return read;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public long skip(long n)
+ throws IOException
+ {
+ // Optimizing the implementation of InputStream.skip(long) sounds like a
+ // nice idea in general. However, we do not expect the method to be used
+ // a lot. Consequently, we would rather go for simplicity.
+ return super.skip(n);
+ }
+
+ /**
+ * Waits on {@link #readSyncRoot} while {@link #inRead} equals
+ * true.
+ */
+ private void waitWhileInRead()
+ {
+ boolean interrupted = false;
+
+ synchronized (readSyncRoot)
+ {
+ while (inRead)
{
try
{
- packets.wait();
+ readSyncRoot.wait();
}
- catch (InterruptedException iex)
+ catch (InterruptedException ex)
{
+ interrupted = true;
}
}
-
- if(currentPacket == null)
- {
- currentPacket = packets.remove(0);
- currentPacketOffset = 0;
- currentPacketLength = currentPacket.length;
- }
-
- }
- return currentPacket;
- }
-
- /**
- * Add packet to this InputStream.
- *
- * @param p packet bytes
- */
- public void addPacket(byte[] p)
- {
- synchronized(packets)
- {
- this.packets.add(p);
- packets.notifyAll();
}
+ if (interrupted)
+ Thread.currentThread().interrupt();
}
}
diff --git a/src/org/ice4j/socket/TCPOutputStream.java b/src/org/ice4j/socket/TCPOutputStream.java
index a62b56f..ed6708b 100644
--- a/src/org/ice4j/socket/TCPOutputStream.java
+++ b/src/org/ice4j/socket/TCPOutputStream.java
@@ -70,26 +70,31 @@ public class TCPOutputStream
public void write(byte[] b, int off, int len)
throws IOException
{
- // GoogleRelayedCandidateSocket will encapsulate data in TURN message
- // so do not add framing here
- if(outputStream instanceof GoogleRelayedCandidateSocket.TCPOutputStream)
+ // GoogleRelayedCandidateSocket will encapsulate data in TURN message so
+ // do not add framing here
+ if (outputStream
+ instanceof GoogleRelayedCandidateSocket.TCPOutputStream)
{
outputStream.write(b, off, len);
- return;
}
+ else
+ {
+ int dataLength = len + 2;
+ byte data[] = new byte[dataLength];
- byte data[] = new byte[len + 2];
- data[0] = (byte)((len >> 8) & 0xff);
- data[1] = (byte)(len & 0xff);
- System.arraycopy(b, off, data, 2, len);
- outputStream.write(data, 0, len + 2);
+ data[0] = (byte) ((len >> 8) & 0xFF);
+ data[1] = (byte) (len & 0xFF);
+ System.arraycopy(b, off, data, 2, len);
+ outputStream.write(data, 0, dataLength);
+ }
}
/**
* {@inheritDoc}
*/
@Override
- public void write(int arg0) throws IOException
+ public void write(int b)
+ throws IOException
{
// TODO Auto-generated method stub
}
diff --git a/test/test/signalling/Signalling.java b/test/test/signalling/Signalling.java
index 1eb7af6..63c125b 100644
--- a/test/test/signalling/Signalling.java
+++ b/test/test/signalling/Signalling.java
@@ -19,9 +19,9 @@ public class Signalling
/**
* The socket where we send and receive signalling
*/
- private final Socket signallingSocket;
+// private final Socket signallingSocket;
- private final SignallingCallback signallingCallback;
+// private final SignallingCallback signallingCallback;
/**
* Creates a signalling instance over the specified socket.
@@ -30,8 +30,8 @@ public class Signalling
*/
public Signalling(Socket socket, SignallingCallback signallingCallback)
{
- this.signallingSocket = socket;
- this.signallingCallback = signallingCallback;
+// this.signallingSocket = socket;
+// this.signallingCallback = signallingCallback;
}
/**