Reduces the number of times that a received packet is internally copied. Reduces the scopes of synchronization blocks and breaks synchronization blocks into multiples on different objects. Optimizes hashtable iterations. Fixes warnings.

This commit is contained in:
lubomir.marinov 2014-10-09 09:47:26 +00:00
parent 9eca04ecad
commit fc0b558497
10 changed files with 1665 additions and 1702 deletions

View File

@ -311,9 +311,16 @@ public class Component
}
catch(Exception e)
{
logger.info("Failed to connect to " +
remoteCandidate.getTransportAddress());
sock.close();
logger.info(
"Failed to connect to "
+ remoteCandidate.getTransportAddress());
try
{
sock.close();
}
catch (IOException ioex)
{
}
return null;
}

View File

@ -6,12 +6,13 @@
*/
package org.ice4j.ice;
import java.net.*;
import java.util.*;
import org.ice4j.*;
import org.ice4j.socket.*;
import org.ice4j.stack.*;
import java.util.*;
/**
* Extends {@link org.ice4j.ice.HostCandidate} allowing the instance to have
* a list of <tt>Socket</tt>s instead of just one socket. This is needed,
@ -27,7 +28,7 @@ public class TcpHostCandidate
* List of <tt>accept</tt>ed sockets for this <tt>TcpHostCandidate</tt>.
*/
private final List<IceSocketWrapper> sockets
= new LinkedList<IceSocketWrapper>();
= new LinkedList<IceSocketWrapper>();
/**
* Initializes a new <tt>TcpHostCandidate</tt>.
@ -40,13 +41,7 @@ public class TcpHostCandidate
public TcpHostCandidate(TransportAddress transportAddress,
Component parentComponent)
{
super(transportAddress,
parentComponent);
}
public List<IceSocketWrapper> getIceSocketWrappers()
{
return sockets;
super(transportAddress, parentComponent);
}
public void addSocket(IceSocketWrapper socket)
@ -59,19 +54,27 @@ public class TcpHostCandidate
{
StunStack stunStack = getStunStack();
TransportAddress localAddr = getTransportAddress();
for (IceSocketWrapper socket : sockets)
{
//remove our sockets from the stack.
Socket tcpSocket = socket.getTCPSocket();
stunStack.removeSocket(
localAddr,
new TransportAddress(
socket.getTCPSocket().getInetAddress(),
socket.getTCPSocket().getPort(),
tcpSocket.getInetAddress(),
tcpSocket.getPort(),
Transport.TCP));
socket.close();
socket.close();
}
super.free();
}
public List<IceSocketWrapper> getIceSocketWrappers()
{
return sockets;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -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 <tt>Socket</tt> 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 <tt>inputStream</tt> into
* <tt>p</tt>, and sets <tt>p</tt>'s port and address to <tt>port</tt> and
* <tt>inetAddress</tt>.
*
* @param p the <tt>DatagramPacket</tt> 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 <tt>ByteBuffer</tt> 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 <tt>Socket</tt>.
*/
@ -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 <tt>ByteBuffer</tt> 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 <tt>DelegatingSocket</tt>.
*/
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 <tt>DelegatingSocket</tt>.
*
* @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 <tt>DelegatingSocket</tt>.
*
* @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 <tt>DatagramPacket</tt>s
* returned by this method do not match any of the
* <tt>DatagramPacketFilter</tt>s of the <tt>MultiplexedSocket</tt>s
* associated with this instance at the time of their receipt. When this
* method returns, the <tt>DatagramPacket</tt>'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.
* <p>
* This method blocks until a datagram is received. The <tt>length</tt>
* 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.
* </p>
*
* @param p the <tt>DatagramPacket</tt> 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 <tt>channel</tt> into
* <tt>p</tt>, and sets <tt>p</tt>'s port and address to the remote port
* and address of this <tt>Socket</tt>.
*/
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 <tt>DatagramPacket</tt> 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 <tt>InputStream</tt>.
*
* @param inputStream <tt>InputStream</tt>
*/
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 <tt>DatagramPacket</tt> 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 <tt>DatagramPacket</tt>s
* returned by this method do not match any of the
* <tt>DatagramPacketFilter</tt>s of the <tt>MultiplexedSocket</tt>s
* associated with this instance at the time of their receipt. When this
* method returns, the <tt>DatagramPacket</tt>'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.
* <p>
* This method blocks until a datagram is received. The <tt>length</tt>
* 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.
* </p>
*
* @param p the <tt>DatagramPacket</tt> 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 <tt>inputStream</tt> into
* <tt>p</tt>, and sets <tt>p</tt>'s port and address to <tt>port</tt> and
* <tt>inetAddress</tt>.
*
* @param p the <tt>DatagramPacket</tt> 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 <tt>channel</tt> into
* <tt>p</tt>, and sets <tt>p</tt>'s port and address to the remote port
* and address of this <tt>Socket</tt>.
*/
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 <tt>InputStream</tt>.
*
* @param inputStream <tt>InputStream</tt>
*/
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).

View File

@ -15,10 +15,9 @@ import java.util.logging.*;
/**
* Represents a <tt>Socket</tt> which receives <tt>DatagramPacket</tt>s
* selected by a <tt>DatagramPacketFilter</tt> from a
* <tt>MultiplexingSocket</tt>. The associated
* <tt>MultiplexingSocket</tt> is the actual <tt>Socket</tt>
* which reads the <tt>DatagramPacket</tt>s from the network. The
* <tt>DatagramPacket</tt>s received through the
* <tt>MultiplexingSocket</tt>. The associated <tt>MultiplexingSocket</tt> is
* the actual <tt>Socket</tt> which reads the <tt>DatagramPacket</tt>s from the
* network. The <tt>DatagramPacket</tt>s received through the
* <tt>MultiplexedSocket</tt> will not be received through the
* associated <tt>MultiplexingSocket</tt>.
*
@ -28,11 +27,12 @@ public class MultiplexedSocket
extends DelegatingSocket
{
/**
* The <tt>Logger</tt> used by the <tt>MultiplexedSocket</tt> class
* and its instances for logging output.
* The <tt>Logger</tt> used by the <tt>MultiplexedSocket</tt> class and its
* instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(MultiplexedSocket.class.getName());
= Logger.getLogger(MultiplexedSocket.class.getName());
/**
* The <tt>DatagramPacketFilter</tt> which determines which
* <tt>DatagramPacket</tt>s read from the network by {@link #multiplexing}
@ -41,8 +41,13 @@ public class MultiplexedSocket
private final DatagramPacketFilter filter;
/**
* The <tt>MultiplexingSocket</tt> which does the actual reading
* from the network and which forwards <tt>DatagramPacket</tt>s accepted by
* The custom <tt>InputStream</tt> for this <tt>MultiplexedSocket</tt>.
*/
private final InputStream inputStream = new InputStreamImpl();
/**
* The <tt>MultiplexingSocket</tt> which does the actual reading from the
* network and which forwards <tt>DatagramPacket</tt>s accepted by
* {@link #filter} for receipt to this instance.
*/
private final MultiplexingSocket multiplexing;
@ -54,20 +59,13 @@ public class MultiplexedSocket
final List<DatagramPacket> received = new LinkedList<DatagramPacket>();
/**
* The custom <tt>InputStream</tt> for this <tt>MultiplexedSocket</tt>.
*/
private final InputStreamImpl inputStream = new InputStreamImpl();
/**
* Initializes a new <tt>MultiplexedSocket</tt> which is unbound and
* filters <tt>DatagramPacket</tt>s away from a specific
* <tt>MultiplexingSocket</tt> using a specific
* <tt>DatagramPacketFilter</tt>.
* Initializes a new <tt>MultiplexedSocket</tt> which is unbound and filters
* <tt>DatagramPacket</tt>s away from a specific <tt>MultiplexingSocket</tt>
* using a specific <tt>DatagramPacketFilter</tt>.
*
* @param multiplexing the <tt>MultiplexingSocket</tt> which does
* the actual reading from the network and which forwards
* <tt>DatagramPacket</tt>s accepted by the specified <tt>filter</tt> to the
* new instance
* @param multiplexing the <tt>MultiplexingSocket</tt> which does the actual
* reading from the network and which forwards <tt>DatagramPacket</tt>s
* accepted by the specified <tt>filter</tt> to the new instance
* @param filter the <tt>DatagramPacketFilter</tt> which determines which
* <tt>DatagramPacket</tt>s read from the network by the specified
* <tt>multiplexing</tt> 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 <tt>DatagramPacketFilter</tt> which determines which
* <tt>DatagramPacket</tt>s 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 <tt>DatagramPacket</tt>'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;
}
}
}

View File

@ -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> 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 <tt>DatagramPacket</tt> instance which is a clone of a
* specific <tt>DatagramPacket</tt> 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;
}

View File

@ -13,10 +13,10 @@ import java.util.*;
import java.util.logging.*;
/**
* Represents a <tt>Socket</tt> which allows filtering
* <tt>DatagramPacket</tt>s it reads from the network using
* <tt>DatagramPacketFilter</tt>s so that the <tt>DatagramPacket</tt>s do not
* get received through it but through associated <tt>MultiplexedSocket</tt>s.
* Represents a <tt>Socket</tt> which allows filtering <tt>DatagramPacket</tt>s
* it reads from the network using <tt>DatagramPacketFilter</tt>s so that the
* <tt>DatagramPacket</tt>s do not get received through it but through
* associated <tt>MultiplexedSocket</tt>s.
*
* @author Sebastien Vincent
* @author Lyubomir Marinov
@ -25,55 +25,54 @@ public class MultiplexingSocket
extends DelegatingSocket
{
/**
* The <tt>Logger</tt> used by the <tt>MultiplexingSocket</tt> class
* and its instances for logging output.
* The <tt>Logger</tt> used by the <tt>MultiplexingSocket</tt> 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
* <tt>MultiplexedSocket</tt> element type. Explicitly defined in
* order to reduce allocations.
* <tt>MultiplexedSocket</tt> element type. Explicitly defined in order to
* reduce allocations.
*/
private static final MultiplexedSocket[] NO_SOCKETS
= new MultiplexedSocket[0];
/**
* The indicator which determines whether this <tt>Socket</tt> is
* currently reading from the network using
* {@link #receive(DatagramPacket)}. When <tt>true</tt>,
* subsequent requests to read from the network will be blocked until the
* current read is finished.
*/
private boolean inReceive = false;
/**
* The list of <tt>DatagramPacket</tt>s to be received through this
* <tt>Socket</tt> i.e. not accepted by the <tt>DatagramFilter</tt>s
* of {@link #sockets} at the time of the reading from the network.
*/
private final List<DatagramPacket> received
= new LinkedList<DatagramPacket>();
/**
* Custom <tt>InputStream</tt> for this <tt>Socket</tt>.
*/
private final TCPInputStream inputStream = new TCPInputStream();
private final InputStream inputStream = new TCPInputStream(this);
/**
* The indicator which determines whether this <tt>Socket</tt> is currently
* reading from the network using {@link #receive(DatagramPacket)}. When
* <tt>true</tt>, subsequent requests to read from the network will be
* blocked until the current read is finished.
*/
private boolean inReceive = false;
/**
* Custom <tt>OutputStream</tt> for this <tt>Socket</tt>.
*/
private TCPOutputStream outputStream = null;
/**
* The list of <tt>DatagramPacket</tt>s to be received through this
* <tt>Socket</tt> i.e. not accepted by the <tt>DatagramFilter</tt>s of
* {@link #sockets} at the time of the reading from the network.
*/
private final List<DatagramPacket> received
= new LinkedList<DatagramPacket>();
/**
* The <tt>Object</tt> which synchronizes the access to {@link #inReceive}.
*/
private final Object receiveSyncRoot = new Object();
/**
* The <tt>MultiplexedSocket</tt>s filtering <tt>DatagramPacket</tt>s
* away from this <tt>Socket</tt>.
* The <tt>MultiplexedSocket</tt>s filtering <tt>DatagramPacket</tt>s away
* from this <tt>Socket</tt>.
*/
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 <tt>setSoTimeout()</tt> call. Altough not strictly needed,
* getting the locally stored value as opposed to retrieving it
* from a parent <tt>getSoTimeout()</tt> call seems to
* significantly improve efficiency, at least on some platforms.
* Buffer variable for storing the SO_TIMEOUT value set by the last
* <tt>setSoTimeout()</tt> call. Although not strictly needed, getting the
* locally stored value as opposed to retrieving it from a parent
* <tt>getSoTimeout()</tt> 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 <tt>MultiplexingSocket</tt> 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 <tt>MultiplexingSocket</tt> 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 <tt>DatagramPacket</tt>s
* returned by this method do not match any of the
* <tt>DatagramPacketFilter</tt>s of the <tt>MultiplexedDatagramSocket</tt>s
* associated with this instance at the time of their receipt. When this
* method returns, the <tt>DatagramPacket</tt>'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.
* <p>
* This method blocks until a datagram is received. The <tt>length</tt>
* 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.
* </p>
*
* @param p the <tt>DatagramPacket</tt> 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 <tt>DatagramPacket</tt> from this <tt>Socket</tt> upon
* request from a specific <tt>MultiplexedSocket</tt>.
*
* @param multiplexed the <tt>MultiplexedSocket</tt> which requests
* the receipt of a <tt>DatagramPacket</tt> from the network
* @param p the <tt>DatagramPacket</tt> 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 <tt>DatagramPacket</tt> from a specific list of
* <tt>DatagramPacket</tt>s if it is not empty or from the network if the
* specified list is empty. When this method returns, the
* <tt>DatagramPacket</tt>'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 <tt>DatagramPacket</tt>
* from which the first is to be removed and returned if available
* @param p the <tt>DatagramPacket</tt> 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<DatagramPacket> 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 <tt>MultiplexedDatagramSocket</tt> which filters
* <tt>DatagramPacket</tt>s away from this <tt>DatagramSocket</tt> using a
* specific <tt>DatagramPacketFilter</tt>. If such a
* <tt>MultiplexedDatagramSocket</tt> does not exist in this instance, it is
* created.
*
* @param filter the <tt>DatagramPacketFilter</tt> to get a
* <tt>MultiplexedDatagramSocket</tt> for
* @return a <tt>MultiplexedDatagramSocket</tt> which filters
* <tt>DatagramPacket</tt>s away from this <tt>DatagramSocket</tt> using the
* specified <tt>filter</tt>
* @throws SocketException if creating the
* <tt>MultiplexedDatagramSocket</tt> for the specified <tt>filter</tt>
* 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 <tt>DatagramPacket</tt>
*/
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 <tt>InputStream</tt>.
*
@ -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 <tt>MultiplexedDatagramSocket</tt> which filters
* <tt>DatagramPacket</tt>s away from this <tt>DatagramSocket</tt> using a
* specific <tt>DatagramPacketFilter</tt>. If such a
* <tt>MultiplexedDatagramSocket</tt> does not exist in this instance, it is
* created.
*
* @param filter the <tt>DatagramPacketFilter</tt> to get a
* <tt>MultiplexedDatagramSocket</tt> for
* @return a <tt>MultiplexedDatagramSocket</tt> which filters
* <tt>DatagramPacket</tt>s away from this <tt>DatagramSocket</tt> using the
* specified <tt>filter</tt>
* @throws SocketException if creating the
* <tt>MultiplexedDatagramSocket</tt> for the specified <tt>filter</tt>
* 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 <tt>DatagramPacket</tt>s
* returned by this method do not match any of the
* <tt>DatagramPacketFilter</tt>s of the <tt>MultiplexedDatagramSocket</tt>s
* associated with this instance at the time of their receipt. When this
* method returns, the <tt>DatagramPacket</tt>'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.
* <p>
* This method blocks until a datagram is received. The <tt>length</tt>
* 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.
* </p>
*
* @param p the <tt>DatagramPacket</tt> 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 <tt>DatagramPacket</tt> from a specific list of
* <tt>DatagramPacket</tt>s if it is not empty or from the network if the
* specified list is empty. When this method returns, the
* <tt>DatagramPacket</tt>'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 <tt>DatagramPacket</tt>
* from which the first is to be removed and returned if available
* @param p the <tt>DatagramPacket</tt> 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<DatagramPacket> 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 <tt>DatagramPacket</tt> from this <tt>Socket</tt> upon
* request from a specific <tt>MultiplexedSocket</tt>.
*
* @param multiplexed the <tt>MultiplexedSocket</tt> which requests
* the receipt of a <tt>DatagramPacket</tt> from the network
* @param p the <tt>DatagramPacket</tt> 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;
}
}

View File

@ -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 <tt>InputStream</tt> interface to users.
* TCP input stream for TCP socket. It is used to multiplex sockets and keep the
* <tt>InputStream</tt> 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 <tt>TCPInputStream</tt> if the
* associated <tt>MultiplexingSocket</tt> does not specify a value.
*/
private final List<byte[]> packets = new ArrayList<byte[]>();
private static final int DEFAULT_RECEIVE_BUFFER_SIZE = 65536;
/**
* The <tt>byte</tt> 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 <tt>TCPInputStream</tt> is
* executing one of its <tt>read</tt> method implementations.
*/
private boolean inRead;
/**
* Current packet being processed if any.
*/
private byte[] currentPacket = null;
private DatagramPacket packet;
/**
* Current offset.
* The <tt>data</tt> 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 <tt>Object</tt> which synchronizes the access to the read-related
* state of this instance.
*/
private final Object readSyncRoot = new Object();
/**
* Initializes a new <tt>TCPInputStream</tt>.
* The <tt>MultiplexingSocket</tt> which has initialized this instance and
* is using it as its <tt>inputStream</tt>.
*/
public TCPInputStream()
{
}
private final MultiplexingSocket socket;
/**
* {@inheritDoc}
* Initializes a new <tt>TCPInputStream</tt>.
*
* @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
* <tt>true</tt>.
*/
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 <tt>InputStream</tt>.
*
* @param p packet bytes
*/
public void addPacket(byte[] p)
{
synchronized(packets)
{
this.packets.add(p);
packets.notifyAll();
}
if (interrupted)
Thread.currentThread().interrupt();
}
}

View File

@ -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
}

View File

@ -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;
}
/**