-fixes few bugs

-code style improvements
-added PseudoTcpSocketFactory(usage changed, see test.IcePseudoTcp example for reference)
This commit is contained in:
paweldomas 2012-08-21 14:24:10 +00:00
parent 139ac8a12f
commit 0856c4dfdf
20 changed files with 1092 additions and 640 deletions

View File

@ -0,0 +1,29 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the Jitsi community (https://jitsi.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.pseudotcp;
/**
* <tt>EnShutdown</tt> enumeration used internally
*
* @author Pawel Domas
*/
enum EnShutdown
{
/**
* There was no shutdown
*/
SD_NONE,
/**
* There was a graceful shutdown
*/
SD_GRACEFUL,
/**
* There was a forceful shutdown
*/
SD_FORCEFUL
};

View File

@ -0,0 +1,33 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the Jitsi community (https://jitsi.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.pseudotcp;
/**
* Options used in PseudoTCP
*
* @author Pawel Domas
*/
public enum Option
{
/**
* Whether to enable Nagle's algorithm (0 == off)
*/
OPT_NODELAY,
/**
* The Delayed ACK timeout (0 == off).
*/
OPT_ACKDELAY,
/**
* Set the receive buffer size, in bytes.
*/
OPT_RCVBUF,
/**
* Set the send buffer size, in bytes.
*/
OPT_SNDBUF,
};

View File

@ -13,10 +13,16 @@ import java.util.logging.*;
import org.ice4j.pseudotcp.util.*; import org.ice4j.pseudotcp.util.*;
/** /**
* Main protocol logic class. To open connection use Connect() method. Then @link(Recv) and @link(Send) operations may be used for data transfer. * Main protocol logic class. To open connection use <tt>connect</tt> method.
* To operate this class requires implementation of @link(IPseudoTcpNotify) * Then <tt>recv</tt> and <tt>send</tt> operations may be used for data transfer.
* To operate this class requires implementation of <tt>PseudoTcpNotify</tt>.
* Also it must be notified about the time progress. * Also it must be notified about the time progress.
* Based on https://developers.google.com/talk/libjingle/
* *
* @see PseudoTCPBase#connect
* @see PseudoTCPBase#recv
* @see PseudoTCPBase#send
* @see PseudoTcpNotify
* @author Pawel Domas * @author Pawel Domas
*/ */
public class PseudoTCPBase public class PseudoTCPBase
@ -263,7 +269,7 @@ public class PseudoTCPBase
*/ */
long m_ack_delay; long m_ack_delay;
boolean m_support_wnd_scale; boolean m_support_wnd_scale;
IPseudoTcpNotify m_notify; PseudoTcpNotify m_notify;
EnShutdown m_shutdown; EnShutdown m_shutdown;
/** /**
* Debug name used to identify peers in log messages * Debug name used to identify peers in log messages
@ -275,10 +281,10 @@ public class PseudoTCPBase
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
/** /**
* *
* @param notify {@link IPseudoTcpNotify} implementation * @param notify {@link PseudoTcpNotify} implementation
* @param conv the conversation number used by this instance * @param conv the conversation number used by this instance
*/ */
public PseudoTCPBase(IPseudoTcpNotify notify, long conv) public PseudoTCPBase(PseudoTcpNotify notify, long conv)
{ {
m_notify = notify; m_notify = notify;
m_shutdown = EnShutdown.SD_NONE; m_shutdown = EnShutdown.SD_NONE;
@ -288,7 +294,7 @@ public class PseudoTCPBase
m_sbuf = new ByteFifoBuffer(m_sbuf_len); m_sbuf = new ByteFifoBuffer(m_sbuf_len);
// Sanity check on buffer sizes (needed for OnTcpWriteable notification logic) // Sanity check on buffer sizes (needed for OnTcpWriteable notification logic)
assert m_rbuf_len + MIN_PACKET < m_sbuf_len; assert m_rbuf_len + MIN_PACKET < m_sbuf_len;
long now = Now(); long now = now();
m_state = PseudoTcpState.TCP_LISTEN; m_state = PseudoTcpState.TCP_LISTEN;
m_conv = conv; m_conv = conv;
@ -332,7 +338,7 @@ public class PseudoTCPBase
* *
* @throws IOException if the protocol is not in initial state * @throws IOException if the protocol is not in initial state
*/ */
public void Connect() throws IOException public void connect() throws IOException
{ {
if (m_state != PseudoTcpState.TCP_LISTEN) if (m_state != PseudoTcpState.TCP_LISTEN)
{ {
@ -352,7 +358,7 @@ public class PseudoTCPBase
* *
* @param mtu * @param mtu
*/ */
public void NotifyMTU(int mtu) public void notifyMTU(int mtu)
{ {
m_mtu_advise = mtu; m_mtu_advise = mtu;
if (m_state == PseudoTcpState.TCP_ESTABLISHED) if (m_state == PseudoTcpState.TCP_ESTABLISHED)
@ -360,34 +366,46 @@ public class PseudoTCPBase
adjustMTU(); adjustMTU();
} }
} }
/**
*
* @return MTU value
*/
public int getMTU()
{
return (int)m_mtu_advise;
}
/** /**
* *
* @return current timestamp limited to 32 bits * @return current timestamp limited to 32 bits
*/ */
public static long Now() public static long now()
{ {
return System.currentTimeMillis() & 0xFFFFFFFFL; return System.currentTimeMillis() & 0xFFFFFFFFL;
} }
/** /**
* Evaluate next interval between @link(GetNextClock) calls. * Evaluate next interval between <tt>getNextClock</tt> calls.
* It is based on current protocol action timeout * It is based on current protocol action timeout
* *
* @param now current timestamp * @param now current timestamp
* @return next interval * @return next interval
*
*/ */
public long GetNextClock(long now) public long getNextClock(long now)
{ {
return clock_check(now); return clock_check(now);
} }
/** /**
* This method should be called in time intervals retrieved from @link(GetNextClock) * This method should be called in time intervals retrieved
* from <tt>getNextClock</tt>
* *
* @param now current timestamp * @param now current timestamp
* @see PseudoTCPBase#getNextClock(long)
*/ */
public void NotifyClock(long now) public void notifyClock(long now)
{ {
if (logger.isLoggable(Level.FINEST)) if (logger.isLoggable(Level.FINEST))
{ {
@ -401,7 +419,7 @@ public class PseudoTCPBase
now = now & 0xFFFFFFFFL; now = now & 0xFFFFFFFFL;
// Check if it's time to retransmit a segment // Check if it's time to retransmit a segment
if (m_rto_base > 0 && (TimeDiff(m_rto_base + m_rx_rto, now) <= 0)) if (m_rto_base > 0 && (timeDiff(m_rto_base + m_rx_rto, now) <= 0))
{ {
assert m_slist.isEmpty() == false; assert m_slist.isEmpty() == false;
// retransmit segments // retransmit segments
@ -430,9 +448,9 @@ public class PseudoTCPBase
} }
// Check if it's time to probe closed windows // Check if it's time to probe closed windows
if ((getM_snd_wnd() == 0) && (TimeDiff(m_lastsend + m_rx_rto, now) <= 0)) if ((getM_snd_wnd() == 0) && (timeDiff(m_lastsend + m_rx_rto, now) <= 0))
{ {
if (TimeDiff(now, m_lastrecv) >= 15000) if (timeDiff(now, m_lastrecv) >= 15000)
{ {
closedown(new IOException("Connection aborted")); closedown(new IOException("Connection aborted"));
return; return;
@ -446,7 +464,7 @@ public class PseudoTCPBase
} }
// Check if it's time to send delayed acks // Check if it's time to send delayed acks
long timeDiff = TimeDiff(m_t_ack + m_ack_delay, now); long timeDiff = timeDiff(m_t_ack + m_ack_delay, now);
if (m_t_ack > 0 && (timeDiff <= 0)) if (m_t_ack > 0 && (timeDiff <= 0))
{ {
packet(m_snd_nxt, (short) 0, 0, 0); packet(m_snd_nxt, (short) 0, 0, 0);
@ -455,7 +473,7 @@ public class PseudoTCPBase
if (PSEUDO_KEEPALIVE) // Check for idle timeout if (PSEUDO_KEEPALIVE) // Check for idle timeout
{ {
if ((m_state == PseudoTcpState.TCP_ESTABLISHED) if ((m_state == PseudoTcpState.TCP_ESTABLISHED)
&& (TimeDiff(m_lastrecv + IDLE_TIMEOUT, now) <= 0)) && (timeDiff(m_lastrecv + IDLE_TIMEOUT, now) <= 0))
{ {
closedown(new IOException("Connection aborted")); closedown(new IOException("Connection aborted"));
return; return;
@ -463,7 +481,7 @@ public class PseudoTCPBase
// Check for ping timeout (to keep udp mapping open) // Check for ping timeout (to keep udp mapping open)
if ((m_state == PseudoTcpState.TCP_ESTABLISHED) if ((m_state == PseudoTcpState.TCP_ESTABLISHED)
&& (TimeDiff(m_lasttraffic + (m_bOutgoing ? IDLE_PING * 3 / 2 : IDLE_PING), now) <= 0)) && (timeDiff(m_lasttraffic + (m_bOutgoing ? IDLE_PING * 3 / 2 : IDLE_PING), now) <= 0))
{ {
packet(m_snd_nxt, (short) 0, 0, 0); packet(m_snd_nxt, (short) 0, 0, 0);
} }
@ -479,7 +497,7 @@ public class PseudoTCPBase
* @param len data length * @param len data length
* @return true if packet was successfully parsed * @return true if packet was successfully parsed
*/ */
synchronized public boolean NotifyPacket(byte[] buffer, int len) synchronized public boolean notifyPacket(byte[] buffer, int len)
{ {
if (len > MAX_PACKET) if (len > MAX_PACKET)
{ {
@ -493,9 +511,9 @@ public class PseudoTCPBase
* Retrieve option's value. See {@link Option} for available options * Retrieve option's value. See {@link Option} for available options
* *
* @param opt option which value will be retrieved * @param opt option which value will be retrieved
* @return * @return option's value
*/ */
long GetOption(Option opt) long getOption(Option opt)
{ {
if (opt == Option.OPT_NODELAY) if (opt == Option.OPT_NODELAY)
{ {
@ -528,7 +546,7 @@ public class PseudoTCPBase
* @param opt option whose value will be set * @param opt option whose value will be set
* @param value the value to be set * @param value the value to be set
*/ */
void SetOption(Option opt, int value) void setOption(Option opt, long value)
{ {
if (opt == Option.OPT_NODELAY) if (opt == Option.OPT_NODELAY)
{ {
@ -545,13 +563,13 @@ public class PseudoTCPBase
if (opt == Option.OPT_SNDBUF) if (opt == Option.OPT_SNDBUF)
{ {
assert m_state == PseudoTcpState.TCP_LISTEN; assert m_state == PseudoTcpState.TCP_LISTEN;
resizeSendBuffer(value); resizeSendBuffer((int)value);
} }
else else
{ {
assert opt == Option.OPT_RCVBUF; assert opt == Option.OPT_RCVBUF;
assert m_state == PseudoTcpState.TCP_LISTEN; assert m_state == PseudoTcpState.TCP_LISTEN;
resizeReceiveBuffer(value); resizeReceiveBuffer((int)value);
} }
} }
} }
@ -561,7 +579,7 @@ public class PseudoTCPBase
* *
* @return congestion window size * @return congestion window size
*/ */
long GetCongestionWindow() long getCongestionWindow()
{ {
return m_cwnd; return m_cwnd;
} }
@ -570,7 +588,7 @@ public class PseudoTCPBase
* *
* @return bytes in flight * @return bytes in flight
*/ */
long GetBytesInFlight() long getBytesInFlight()
{ {
return m_snd_nxt - m_snd_una; return m_snd_nxt - m_snd_una;
} }
@ -579,9 +597,9 @@ public class PseudoTCPBase
* *
* @return bytes buffered, but not sent yet * @return bytes buffered, but not sent yet
*/ */
long GetBytesBufferedNotSent() long getBytesBufferedNotSent()
{ {
long buffered_bytes = m_sbuf.GetBuffered(); long buffered_bytes = m_sbuf.getBuffered();
return m_snd_una + buffered_bytes - m_snd_nxt; return m_snd_una + buffered_bytes - m_snd_nxt;
} }
@ -589,25 +607,25 @@ public class PseudoTCPBase
* *
* @return bytes available in receive buffer * @return bytes available in receive buffer
*/ */
int GetAvailable() int getAvailable()
{ {
return m_rbuf.GetBuffered(); return m_rbuf.getBuffered();
} }
/** /**
* *
* @return space available in the send buffer * @return space available in the send buffer
*/ */
int GetAvailableSendBuffer() int getAvailableSendBuffer()
{ {
return m_sbuf.GetWriteRemaining(); return m_sbuf.getWriteRemaining();
} }
/** /**
* *
* @return round trip time estimate in ms * @return round trip time estimate in ms
*/ */
long GetRoundTripTimeEstimateMs() long getRoundTripTimeEstimateMs()
{ {
return m_rx_srtt; return m_rx_srtt;
} }
@ -622,14 +640,14 @@ public class PseudoTCPBase
* @return byte count actually read * @return byte count actually read
* @throws IOException if the protocol is not in the connected state * @throws IOException if the protocol is not in the connected state
*/ */
public synchronized int Recv(byte[] buffer, int offset, int len) throws IOException public synchronized int recv(byte[] buffer, int offset, int len) throws IOException
{ {
if (m_state != PseudoTcpState.TCP_ESTABLISHED) if (m_state != PseudoTcpState.TCP_ESTABLISHED)
{ {
throw new IOException("Socket not connected"); throw new IOException("Socket not connected");
} }
int read = m_rbuf.Read(buffer, offset, len); int read = m_rbuf.read(buffer, offset, len);
// If there's no data in |m_rbuf|. // If there's no data in |m_rbuf|.
if (read == 0) if (read == 0)
@ -639,7 +657,7 @@ public class PseudoTCPBase
} }
assert read != -1; assert read != -1;
int available_space = m_rbuf.GetWriteRemaining(); int available_space = m_rbuf.getWriteRemaining();
if (available_space - m_rcv_wnd >= Math.min(m_rbuf_len / 8, m_mss)) if (available_space - m_rcv_wnd >= Math.min(m_rbuf_len / 8, m_mss))
{ {
boolean bWasClosed = (m_rcv_wnd == 0); // !?! Not sure about this was closed business boolean bWasClosed = (m_rcv_wnd == 0); // !?! Not sure about this was closed business
@ -657,24 +675,24 @@ public class PseudoTCPBase
* *
* @param buffer * @param buffer
* @param len * @param len
* @return * @return received byte count
* @throws IOException * @throws IOException
*/ */
public int Recv(byte[] buffer, int len) throws IOException public int recv(byte[] buffer, int len) throws IOException
{ {
return Recv(buffer, 0, len); return recv(buffer, 0, len);
} }
/** /**
* *
* @param buffer * @param buffer
* @param len * @param len
* @return * @return sent byte count
* @throws IOException * @throws IOException
*/ */
public int Send(byte[] buffer, int len) throws IOException public int send(byte[] buffer, int len) throws IOException
{ {
return Send(buffer, 0, len); return send(buffer, 0, len);
} }
/** /**
@ -686,7 +704,7 @@ public class PseudoTCPBase
* @return bytes count written to the send buffer * @return bytes count written to the send buffer
* @throws IOException if the protocol is not in connected state * @throws IOException if the protocol is not in connected state
*/ */
public synchronized int Send(byte[] buffer, int offset, int len) public synchronized int send(byte[] buffer, int offset, int len)
throws IOException throws IOException
{ {
if (m_state != PseudoTcpState.TCP_ESTABLISHED) if (m_state != PseudoTcpState.TCP_ESTABLISHED)
@ -695,7 +713,7 @@ public class PseudoTCPBase
} }
long available_space; long available_space;
available_space = m_sbuf.GetWriteRemaining(); available_space = m_sbuf.getWriteRemaining();
if (available_space == 0) if (available_space == 0)
{ {
@ -713,7 +731,7 @@ public class PseudoTCPBase
* *
* @param force if true all data received from this moment will be discarded * @param force if true all data received from this moment will be discarded
*/ */
public void Close(boolean force) void close(boolean force)
{ {
logger.log(Level.FINE, debugName + " close (" + force + ")"); logger.log(Level.FINE, debugName + " close (" + force + ")");
m_shutdown = force ? EnShutdown.SD_FORCEFUL : EnShutdown.SD_GRACEFUL; m_shutdown = force ? EnShutdown.SD_FORCEFUL : EnShutdown.SD_GRACEFUL;
@ -738,7 +756,7 @@ public class PseudoTCPBase
int queue(byte[] buffer, int offset, int len, boolean bCtrl) int queue(byte[] buffer, int offset, int len, boolean bCtrl)
{ {
int available_space; int available_space;
available_space = m_sbuf.GetWriteRemaining(); available_space = m_sbuf.getWriteRemaining();
if (len > available_space) if (len > available_space)
{ {
assert !bCtrl; assert !bCtrl;
@ -759,7 +777,7 @@ public class PseudoTCPBase
else else
{ {
long snd_buffered; long snd_buffered;
snd_buffered = m_sbuf.GetBuffered(); snd_buffered = m_sbuf.getBuffered();
SSegment sseg = new SSegment( SSegment sseg = new SSegment(
m_snd_una + snd_buffered, m_snd_una + snd_buffered,
len, len,
@ -773,25 +791,28 @@ public class PseudoTCPBase
m_slist.add(sseg); m_slist.add(sseg);
} }
int written = m_sbuf.Write(buffer, offset, len); int written = m_sbuf.write(buffer, offset, len);
return written; return written;
} }
/** /**
* Creates a packet starting at <tt>offset</tt> in the send buffer of * Creates a packet starting at <tt>offset</tt> in the send buffer of
* specified length and sends it with help of @link(IPseudoTcpNotify). * specified length and sends it with help of <tt>PseudoTcpNotify</tt>.
* *
* @param seq used sequence number * @param seq used sequence number
* @param flags * @param flags
* @param offset in the send buffer * @param offset in the send buffer
* @param len length of data from * @param len length of data from
* @return @link(WriteResult) returned by @link(IPseudoTcpNotify) * @return <tt>WriteResult</tt> returned by <tt>PseudoTcpNotify</tt>
*
* @see PseudoTcpNotify
* @see WriteResult
*/ */
WriteResult packet(long seq, short flags, long offset, long len) WriteResult packet(long seq, short flags, long offset, long len)
{ {
assert HEADER_SIZE + len <= MAX_PACKET; assert HEADER_SIZE + len <= MAX_PACKET;
long now = Now(); long now = now();
byte[] buffer = new byte[HEADER_SIZE + (int)len]; byte[] buffer = new byte[HEADER_SIZE + (int)len];
long_to_bytes(m_conv, buffer, 0); long_to_bytes(m_conv, buffer, 0);
@ -808,7 +829,7 @@ public class PseudoTCPBase
if (len > 0) if (len > 0)
{ {
int bytes_read = m_sbuf.ReadOffset(buffer, HEADER_SIZE, int bytes_read = m_sbuf.readOffset(buffer, HEADER_SIZE,
(int) len, (int) len,
(int) offset); (int) offset);
assert bytes_read == len; assert bytes_read == len;
@ -820,7 +841,7 @@ public class PseudoTCPBase
+ "<WND=" + m_rcv_wnd + "><SCALE=" + m_rwnd_scale + "><TS=" + now + "<WND=" + m_rcv_wnd + "><SCALE=" + m_rwnd_scale + "><TS=" + now
+ "><TSR=" + m_ts_recent + "><LEN=" + len + ">"); + "><TSR=" + m_ts_recent + "><LEN=" + len + ">");
} }
WriteResult wres = m_notify.TcpWritePacket(this, WriteResult wres = m_notify.tcpWritePacket(this,
buffer, buffer,
(int) len + HEADER_SIZE); (int) len + HEADER_SIZE);
/** /**
@ -845,9 +866,9 @@ public class PseudoTCPBase
} }
/** /**
* Method can be used in some debugging utilities * Method can be used in debugging utilities to parse PTCP segment
*/ */
public static String parseSeg(byte[] buffer, int size) public static Segment parseSeg(byte[] buffer, int size)
{ {
if (size < 12) if (size < 12)
{ {
@ -866,15 +887,27 @@ public class PseudoTCPBase
seg.data = copy_buffer(buffer, HEADER_SIZE, size - HEADER_SIZE); seg.data = copy_buffer(buffer, HEADER_SIZE, size - HEADER_SIZE);
seg.len = size - HEADER_SIZE; seg.len = size - HEADER_SIZE;
return seg;
}
/**
* Can be used to convert segments to text
*
* @param seg
* @return segment in readable text form
*/
public static String segToStr(Segment seg)
{
String data="data: "; String data="data: ";
for(byte b : seg.data) for(byte b : seg.data)
{ {
data += b; data += b;
} }
return "segment " + "<CONV=" + seg.conv + "><FLG=" + seg.flags return "<CONV=" + seg.conv + "><FLG=" + seg.flags + "><SEQ="
+ "><SEQ=" + seg.seq + ":" + (seg.seq + seg.len) + "><ACK=" + seg.ack + seg.seq + ":" + (seg.seq + seg.len) + "><ACK=" + seg.ack
+ "><WND=" + seg.wnd + "><TS=" + seg.tsval + "><WND=" + seg.wnd + "><TS=" + seg.tsval
+ "><TSR=" + seg.tsecr + "><LEN=" + seg.len + "> "+data; + "><TSR=" + seg.tsecr + "><LEN=" + seg.len + "> "+data;
} }
/** /**
@ -892,18 +925,7 @@ public class PseudoTCPBase
return false; return false;
} }
Segment seg = new Segment(); Segment seg = parseSeg(buffer, size);
seg.conv = bytes_to_long(buffer, 0);
seg.seq = bytes_to_long(buffer, 4);
seg.ack = bytes_to_long(buffer, 8);
seg.flags = buffer[13];
seg.wnd = bytes_to_short(buffer, 14);
seg.tsval = bytes_to_long(buffer, 16);
seg.tsecr = bytes_to_long(buffer, 20);
seg.data = copy_buffer(buffer, HEADER_SIZE, size - HEADER_SIZE);
seg.len = size - HEADER_SIZE;
if (logger.isLoggable(Level.FINE)) if (logger.isLoggable(Level.FINE))
{ {
@ -931,7 +953,7 @@ public class PseudoTCPBase
long nTimeout; long nTimeout;
long snd_buffered; long snd_buffered;
snd_buffered = m_sbuf.GetBuffered(); snd_buffered = m_sbuf.getBuffered();
if ((m_shutdown == EnShutdown.SD_GRACEFUL) if ((m_shutdown == EnShutdown.SD_GRACEFUL)
&& ((m_state != PseudoTcpState.TCP_ESTABLISHED) && ((m_state != PseudoTcpState.TCP_ESTABLISHED)
|| ((snd_buffered == 0) && (m_t_ack == 0)))) || ((snd_buffered == 0) && (m_t_ack == 0))))
@ -948,15 +970,15 @@ public class PseudoTCPBase
if (m_t_ack > 0) if (m_t_ack > 0)
{ {
nTimeout = Math.min(nTimeout, TimeDiff(m_t_ack + m_ack_delay, now)); nTimeout = Math.min(nTimeout, timeDiff(m_t_ack + m_ack_delay, now));
} }
if (m_rto_base > 0) if (m_rto_base > 0)
{ {
nTimeout = Math.min(nTimeout, TimeDiff(m_rto_base + m_rx_rto, now)); nTimeout = Math.min(nTimeout, timeDiff(m_rto_base + m_rx_rto, now));
} }
if (getM_snd_wnd() == 0) if (getM_snd_wnd() == 0)
{ {
nTimeout = Math.min(nTimeout, TimeDiff(m_lastsend + m_rx_rto, now)); nTimeout = Math.min(nTimeout, timeDiff(m_lastsend + m_rx_rto, now));
} }
if (PSEUDO_KEEPALIVE) if (PSEUDO_KEEPALIVE)
{ {
@ -964,7 +986,7 @@ public class PseudoTCPBase
{ {
nTimeout = Math.min( nTimeout = Math.min(
nTimeout, nTimeout,
TimeDiff(m_lasttraffic + (m_bOutgoing ? IDLE_PING * 3 / 2 : IDLE_PING), now)); timeDiff(m_lasttraffic + (m_bOutgoing ? IDLE_PING * 3 / 2 : IDLE_PING), now));
} }
} }
//nTimeout is used on wait methods, so cannot be equal to 0 //nTimeout is used on wait methods, so cannot be equal to 0
@ -993,7 +1015,7 @@ public class PseudoTCPBase
return false; return false;
} }
long now = Now(); long now = now();
m_lasttraffic = m_lastrecv = now; m_lasttraffic = m_lastrecv = now;
m_bOutgoing = false; m_bOutgoing = false;
@ -1048,7 +1070,7 @@ public class PseudoTCPBase
adjustMTU(); adjustMTU();
if (m_notify != null) if (m_notify != null)
{ {
m_notify.OnTcpOpen(this); m_notify.onTcpOpen(this);
} }
//notify(evOpen); //notify(evOpen);
} }
@ -1075,7 +1097,7 @@ public class PseudoTCPBase
// Calculate round-trip time // Calculate round-trip time
if (seg.tsecr > 0) if (seg.tsecr > 0)
{ {
long rtt = TimeDiff(now, seg.tsecr); long rtt = timeDiff(now, seg.tsecr);
assert rtt >= 0; assert rtt >= 0;
if (m_rx_srtt == 0) if (m_rx_srtt == 0)
{ {
@ -1106,7 +1128,7 @@ public class PseudoTCPBase
m_rto_base = (m_snd_una == m_snd_nxt) ? 0 : now; m_rto_base = (m_snd_una == m_snd_nxt) ? 0 : now;
m_sbuf.ConsumeReadData((int) nAcked); m_sbuf.consumeReadData((int) nAcked);
synchronized (ack_notify) synchronized (ack_notify)
{ {
if (logger.isLoggable(Level.FINER)) if (logger.isLoggable(Level.FINER))
@ -1237,7 +1259,7 @@ public class PseudoTCPBase
adjustMTU(); adjustMTU();
if (m_notify != null) if (m_notify != null)
{ {
m_notify.OnTcpOpen(this); m_notify.onTcpOpen(this);
} }
//notify(evOpen); //notify(evOpen);
} }
@ -1245,13 +1267,13 @@ public class PseudoTCPBase
// The goal it to make sure we always have at least enough data to fill the // The goal it to make sure we always have at least enough data to fill the
// window. We'd like to notify the app when we are halfway to that point. // window. We'd like to notify the app when we are halfway to that point.
long kIdealRefillSize = (m_sbuf_len + m_rbuf_len) / 2; long kIdealRefillSize = (m_sbuf_len + m_rbuf_len) / 2;
long snd_buffered = m_sbuf.GetBuffered(); long snd_buffered = m_sbuf.getBuffered();
if (m_bWriteEnable && snd_buffered < kIdealRefillSize) if (m_bWriteEnable && snd_buffered < kIdealRefillSize)
{ {
m_bWriteEnable = false; m_bWriteEnable = false;
if (m_notify != null) if (m_notify != null)
{ {
m_notify.OnTcpWriteable(this); m_notify.onTcpWriteable(this);
} }
//notify(evWrite); //notify(evWrite);
} }
@ -1303,7 +1325,7 @@ public class PseudoTCPBase
if (nAdjust < seg.len) if (nAdjust < seg.len)
{ {
seg.seq += nAdjust; seg.seq += nAdjust;
seg.data = ScrollBuffer(seg.data, nAdjust); seg.data = scrollBuffer(seg.data, (int)nAdjust);
seg.len -= nAdjust; seg.len -= nAdjust;
} }
else else
@ -1311,7 +1333,7 @@ public class PseudoTCPBase
seg.len = 0; seg.len = 0;
} }
} }
long available_space = m_rbuf.GetWriteRemaining(); long available_space = m_rbuf.getWriteRemaining();
if ((seg.seq + seg.len - m_rcv_nxt) > available_space) if ((seg.seq + seg.len - m_rcv_nxt) > available_space)
{ {
long nAdjust = seg.seq + seg.len - m_rcv_nxt - available_space; long nAdjust = seg.seq + seg.len - m_rcv_nxt - available_space;
@ -1339,7 +1361,7 @@ public class PseudoTCPBase
{ {
long nOffset = seg.seq - m_rcv_nxt; long nOffset = seg.seq - m_rcv_nxt;
int result = m_rbuf.WriteOffset(seg.data, seg.len, int result = m_rbuf.writeOffset(seg.data, seg.len,
(int) nOffset); (int) nOffset);
assert result == seg.len; assert result == seg.len;
@ -1351,7 +1373,7 @@ public class PseudoTCPBase
"Avail space: " + available_space "Avail space: " + available_space
+ " seg.len: " + seg.len); + " seg.len: " + seg.len);
} }
m_rbuf.ConsumeWriteBuffer(seg.len); m_rbuf.consumeWriteBuffer(seg.len);
m_rcv_nxt += seg.len; m_rcv_nxt += seg.len;
m_rcv_wnd -= seg.len; m_rcv_wnd -= seg.len;
bNewData = true; bNewData = true;
@ -1377,7 +1399,7 @@ public class PseudoTCPBase
+ m_rcv_nxt + " -> " + (m_rcv_nxt + nAdjust) + m_rcv_nxt + " -> " + (m_rcv_nxt + nAdjust)
+ ")"); + ")");
} }
m_rbuf.ConsumeWriteBuffer((int) nAdjust); m_rbuf.consumeWriteBuffer((int) nAdjust);
m_rcv_nxt += nAdjust; m_rcv_nxt += nAdjust;
m_rcv_wnd -= nAdjust; m_rcv_wnd -= nAdjust;
} }
@ -1415,7 +1437,7 @@ public class PseudoTCPBase
m_bReadEnable = false; m_bReadEnable = false;
if (m_notify != null) if (m_notify != null)
{ {
m_notify.OnTcpReadable(this); m_notify.onTcpReadable(this);
} }
//notify(evRead); //notify(evRead);
} }
@ -1429,7 +1451,7 @@ public class PseudoTCPBase
* @param earlier timestamp in ms * @param earlier timestamp in ms
* @return difference between <tt>later</tt> and <tt>earlier</tt> * @return difference between <tt>later</tt> and <tt>earlier</tt>
*/ */
private static long TimeDiff(long later, long earlier) private static long timeDiff(long later, long earlier)
{ {
return later - earlier; return later - earlier;
} }
@ -1527,10 +1549,11 @@ public class PseudoTCPBase
return Math.min(Math.max(lower, middle), upper); return Math.min(Math.max(lower, middle), upper);
} }
private byte[] ScrollBuffer(byte[] data, long nAdjust) private byte[] scrollBuffer(byte[] data, int nAdjust)
{ {
//TODO: never been hit so far, to be implemented byte[] newBuffer = new byte[data.length - nAdjust];
throw new UnsupportedOperationException("Not yet implemented"); System.arraycopy(data, nAdjust, newBuffer, 0, newBuffer.length);
return newBuffer;
} }
/** /**
@ -1634,9 +1657,9 @@ public class PseudoTCPBase
*/ */
void attemptSend(SendFlags sflags) void attemptSend(SendFlags sflags)
{ {
long now = Now(); long now = now();
if (TimeDiff(now, m_lastsend) > m_rx_rto) if (timeDiff(now, m_lastsend) > m_rx_rto)
{ {
m_cwnd = m_mss; m_cwnd = m_mss;
} }
@ -1653,7 +1676,7 @@ public class PseudoTCPBase
long nInFlight = m_snd_nxt - m_snd_una; long nInFlight = m_snd_nxt - m_snd_una;
long nUseable = (nInFlight < nWindow) ? (nWindow - nInFlight) : 0; long nUseable = (nInFlight < nWindow) ? (nWindow - nInFlight) : 0;
long snd_buffered = m_sbuf.GetBuffered(); long snd_buffered = m_sbuf.getBuffered();
/* /*
* System.out.println("is available? buffered: " + snd_buffered + " * System.out.println("is available? buffered: " + snd_buffered + "
* inFlight: " + nInFlight + " m_mss: " + m_mss + " m_snd_wnd: " + * inFlight: " + nInFlight + " m_mss: " + m_mss + " m_snd_wnd: " +
@ -1679,7 +1702,7 @@ public class PseudoTCPBase
if (bFirst) if (bFirst)
{ {
long available_space = m_sbuf.GetWriteRemaining(); long available_space = m_sbuf.getWriteRemaining();
bFirst = false; bFirst = false;
if (logger.isLoggable(Level.FINE)) if (logger.isLoggable(Level.FINE))
@ -1708,7 +1731,7 @@ public class PseudoTCPBase
} }
else else
{ {
m_t_ack = Now(); m_t_ack = now();
logger.log(Level.FINER, "Delayed ack, m_t_ack: " + m_t_ack); logger.log(Level.FINER, "Delayed ack, m_t_ack: " + m_t_ack);
} }
return; return;
@ -1781,7 +1804,7 @@ public class PseudoTCPBase
m_state = PseudoTcpState.TCP_CLOSED; m_state = PseudoTcpState.TCP_CLOSED;
if (m_notify != null) if (m_notify != null)
{ {
m_notify.OnTcpClosed(this, e); m_notify.onTcpClosed(this, e);
} }
} }
@ -1813,7 +1836,7 @@ public class PseudoTCPBase
*/ */
boolean isReceiveBufferFull() boolean isReceiveBufferFull()
{ {
return m_rbuf.GetWriteRemaining() == 0; return m_rbuf.getWriteRemaining() == 0;
} }
/** /**
@ -1961,7 +1984,7 @@ public class PseudoTCPBase
void resizeSendBuffer(int new_size) void resizeSendBuffer(int new_size)
{ {
m_sbuf_len = new_size; m_sbuf_len = new_size;
m_sbuf.SetCapacity(new_size); m_sbuf.setCapacity(new_size);
} }
/** /**
@ -1983,7 +2006,7 @@ public class PseudoTCPBase
// Determine the proper size of the buffer. // Determine the proper size of the buffer.
new_size <<= scale_factor; new_size <<= scale_factor;
boolean result = m_rbuf.SetCapacity(new_size); boolean result = m_rbuf.setCapacity(new_size);
// Make sure the new buffer is large enough to contain data in the old // Make sure the new buffer is large enough to contain data in the old
// buffer. This should always be true because this method is called either // buffer. This should always be true because this method is called either
@ -1994,7 +2017,7 @@ public class PseudoTCPBase
m_rwnd_scale = scale_factor; m_rwnd_scale = scale_factor;
m_ssthresh = new_size; m_ssthresh = new_size;
int available_space = m_rbuf.GetWriteRemaining(); int available_space = m_rbuf.getWriteRemaining();
m_rcv_wnd = available_space; m_rcv_wnd = available_space;
} }
@ -2050,119 +2073,22 @@ public class PseudoTCPBase
} }
private final Object ack_notify = new Object(); private final Object ack_notify = new Object();
public Object GetAckNotify() public Object getAckNotify()
{ {
return ack_notify; return ack_notify;
} }
}
/** long getConversationID()
* Class used internally as a structure for receive segments
*
* @author Pawel
*/
class RSegment
{
public long seq, len;
public RSegment(long seq, long len)
{ {
this.seq = seq; return m_conv;
this.len = len;
} }
}
/** void setConversationID(long convID)
* Class used internally as a structure for send segments
*
* @author Pawel Domas
*/
class SSegment
{
long seq, len;
//uint32 tstamp;
short xmit;
boolean bCtrl;
SSegment(long s, long l, boolean c)
{ {
seq = s; if(m_state != PseudoTcpState.TCP_LISTEN)
len = l; throw new IllegalStateException();
xmit = 0; this.m_conv = convID;
bCtrl = c;
} }
} }
/**
* Shutdown enum used internally
*
* @author Pawel Domas
*/
enum EnShutdown
{
/**
* There was no shutdown
*/
SD_NONE,
/**
* There was a graceful shutdown
*/
SD_GRACEFUL,
/**
* There was a forceful shutdown
*/
SD_FORCEFUL
};
/**
* Options used in pseudotcp
*
* @author Pawel Domas
*/
enum Option
{
/**
* Whether to enable Nagle's algorithm (0 == off)
*/
OPT_NODELAY,
/**
* The Delayed ACK timeout (0 == off).
*/
OPT_ACKDELAY,
/**
* Set the receive buffer size, in bytes.
*/
OPT_RCVBUF,
/**
* Set the send buffer size, in bytes.
*/
OPT_SNDBUF,
};
/**
* Send flags used internally
*
* @author Pawel Domas
*/
enum SendFlags
{
sfNone, sfImmediateAck, sfDelayedAck;
}
/**
* Class used internally as a segment structure
*
* @author Pawel Domas
*/
class Segment
{
long conv;
long seq;
long ack;
byte flags;
int wnd;
long tsval;
long tsecr;
byte[] data;
int len;
}

View File

@ -0,0 +1,53 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the Jitsi community (https://jitsi.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.pseudotcp;
import java.io.*;
/**
* Notification of tcp events.
* Is implemented by <tt>PseudoTcpSocketImpl</tt> to expose stream functionality.
*
* @author Pawel Domas
*/
public interface PseudoTcpNotify
{
/**
* Called when TCP enters opened state
* @param tcp
*/
void onTcpOpen(PseudoTCPBase tcp);
/**
* Called when any data is available in read buffer
* @param tcp
*/
void onTcpReadable(PseudoTCPBase tcp);
/**
* Called when there is free space available in the send buffer
* @param tcp
*/
void onTcpWriteable(PseudoTCPBase tcp);
/**
* Called when tcp enters closed state
* @param tcp
* @param e null means no error
*/
void onTcpClosed(PseudoTCPBase tcp, IOException e);
/**
* Called when protocol requests packet transfer through the network.
* @param tcp
* @param buffer data
* @param len data length
* @return the result, see {@link WriteResult} description for more info
*/
WriteResult tcpWritePacket(PseudoTCPBase tcp, byte[] buffer, int len);
}

View File

@ -0,0 +1,135 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the Jitsi community (https://jitsi.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.pseudotcp;
import java.io.*;
import java.net.*;
/**
*
* @author Pawel Domas
*/
public class PseudoTcpSocket extends Socket
{
private final PseudoTcpSocketImpl socketImpl;
PseudoTcpSocket(PseudoTcpSocketImpl socketImpl)
throws SocketException
{
super(socketImpl);
this.socketImpl = socketImpl;
}
/**
*
* @return PseudoTCP conversation ID
*/
public long getConversationID()
{
return socketImpl.getConversationID();
}
/**
* Set conversation ID for the socket
* Must be called on unconnected socket
*
* @param convID
* @throws IllegalStateException when called on connected or closed socket
*/
public void setConversationID(long convID)
throws IllegalStateException
{
socketImpl.setConversationID(convID);
}
/**
* Sets MTU value
* @param mtu
*/
public void setMTU(int mtu)
{
socketImpl.setMTU(mtu);
}
/**
*
* @return MTU value
*/
public int getMTU()
{
return socketImpl.getMTU();
}
/**
*
* @return PseudoTCP option value
*
* @see Option
*/
public long getOption(Option option)
{
return socketImpl.getPTCPOption(option);
}
/**
*
* @param option PseudoTCP option to set
* @param optValue option's value
*
* @see Option
*/
public void setOption(Option option, long optValue)
{
socketImpl.setPTCPOption(option, optValue);
}
/**
* Blocking method waits for connection.
*
* @param timeout for this operation in ms
* @throws IOException If socket gets closed or timeout expires
*/
public void accept(int timeout)
throws IOException
{
socketImpl.accept(timeout);
}
/**
* Sets debug name that will be displayed in log messages for this socket
* @param debugName
*/
public void setDebugName(String debugName)
{
socketImpl.setDebugName(debugName);
}
/**
* Returns current <tt>PseudoTcpState</tt> of this socket
* @return current <tt>PseudoTcpState</tt>
*
* @see PseudoTcpState
*/
public PseudoTcpState getState()
{
return socketImpl.getState();
}
@Override
public boolean isConnected()
{
return getState() == PseudoTcpState.TCP_ESTABLISHED;
}
@Override
public boolean isClosed()
{
return getState() == PseudoTcpState.TCP_CLOSED;
}
}

View File

@ -0,0 +1,138 @@
package org.ice4j.pseudotcp;
import java.io.*;
import java.net.*;
import javax.net.*;
public class PseudoTcpSocketFactory
extends SocketFactory
implements SocketImplFactory
{
/**
* Default conversation ID
*/
public static final long DEFAULT_CONVERSATION_ID=0;
/**
* Default timeout for connect operation
*/
public static final int DEFAULT_CONNECT_TIMEOUT=5000;
/**
* Creates a socket and connects it to the specified
* port number at the specified address.
*/
@Override
public Socket createSocket(String host, int port)
throws IOException,
UnknownHostException
{
Socket socket = createSocket();
connectSocket(socket, new InetSocketAddress(host, port));
return socket;
}
/**
* Creates a socket and connect it to the specified remote address
* on the specified remote port.
*/
@Override
public Socket createSocket(InetAddress host, int port) throws IOException
{
Socket socket = createSocket();
connectSocket(socket, new InetSocketAddress(host, port));
return socket;
}
private void connectSocket(Socket socket, InetSocketAddress remoteSockAddr)
throws IOException
{
socket.connect(remoteSockAddr, DEFAULT_CONNECT_TIMEOUT);
}
/**
* Creates socket bound to local <tt>sockAddr</tt>
* @param sockAddr
* @return socket bound to local address
* @throws IOException
*/
public Socket createBoundSocket(InetSocketAddress sockAddr)
throws IOException
{
return new PseudoTcpSocket(
new PseudoTcpSocketImpl(DEFAULT_CONVERSATION_ID,
new DatagramSocket(sockAddr)));
}
/**
* Creates a socket and connects it to the specified remote host at the specified remote port.
*/
@Override
public Socket createSocket(String host,
int port,
InetAddress localHost,
int localPort)
throws IOException,
UnknownHostException
{
Socket socket = createBoundSocket(
new InetSocketAddress(localHost, localPort));
connectSocket(socket, new InetSocketAddress(host, port));
return socket;
}
/**
* Creates a socket and connects it to the specified remote host on the specified remote port.
*/
@Override
public Socket createSocket(InetAddress address, int port,
InetAddress localAddress, int localPort) throws IOException
{
Socket socket = createBoundSocket(
new InetSocketAddress(localAddress, localPort));
connectSocket(socket, new InetSocketAddress(address, port));
return socket;
}
/**
* Creates a socket that will run on given <tt>datagramSocket</tt>
*
* @param datagramSocket
* @return new socket running on given <tt>datagramSocket</tt>
* @throws SocketException
*/
public PseudoTcpSocket createSocket(DatagramSocket datagramSocket)
throws SocketException
{
return new PseudoTcpSocket(
new PseudoTcpSocketImpl(DEFAULT_CONVERSATION_ID, datagramSocket));
}
/**
* Creates the PseudoTcp socket and binds it to any available port
* on the local host machine. The socket will be bound to the
* {@link InetAddress#isAnyLocalAddress wildcard} address,
* an IP address chosen by the kernel.
*
*/
public PseudoTcpSocket createSocket()
throws SocketException
{
return new PseudoTcpSocket(
new PseudoTcpSocketImpl(DEFAULT_CONVERSATION_ID));
}
@Override
public SocketImpl createSocketImpl()
{
try
{
return new PseudoTcpSocketImpl(DEFAULT_CONVERSATION_ID);
}
catch (SocketException e)
{
throw new RuntimeException(e);
}
}
}

View File

@ -12,9 +12,9 @@ import java.net.*;
import java.util.*; import java.util.*;
import java.util.logging.*; import java.util.logging.*;
public class PseudoTcpSocketImpl class PseudoTcpSocketImpl
extends SocketImpl extends SocketImpl
implements IPseudoTcpNotify implements PseudoTcpNotify
{ {
/** /**
* The logger. * The logger.
@ -138,7 +138,26 @@ public class PseudoTcpSocketImpl
*/ */
public void setMTU(int mtu) public void setMTU(int mtu)
{ {
this.pseudoTcp.NotifyMTU(mtu); this.pseudoTcp.notifyMTU(mtu);
}
/**
*
* @return current MTU set
*/
public int getMTU()
{
return pseudoTcp.getMTU();
}
long getConversationID()
{
return pseudoTcp.getConversationID();
}
void setConversationID(long convID)
{
pseudoTcp.setConversationID(convID);
} }
/** /**
@ -170,7 +189,7 @@ public class PseudoTcpSocketImpl
protected void connect(String host, int port) protected void connect(String host, int port)
throws IOException throws IOException
{ {
Connect(new InetSocketAddress(InetAddress.getByName(host), port), 0); doConnect(new InetSocketAddress(InetAddress.getByName(host), port), 0);
} }
/** /**
@ -197,7 +216,7 @@ public class PseudoTcpSocketImpl
throws IOException throws IOException
{ {
InetSocketAddress inetAddr = (InetSocketAddress) address; InetSocketAddress inetAddr = (InetSocketAddress) address;
Connect(inetAddr, timeout); doConnect(inetAddr, timeout);
} }
/** /**
@ -233,15 +252,27 @@ public class PseudoTcpSocketImpl
public void setOption(int optID, Object value) public void setOption(int optID, Object value)
throws SocketException throws SocketException
{ {
//TODO: map options to PTCP options/method calls
options.put(optID, value); options.put(optID, value);
} }
public Object getOption(int optID) public Object getOption(int optID)
throws SocketException throws SocketException
{ {
//TODO: map options to PTCP options/method calls
return options.get(optID); return options.get(optID);
} }
public long getPTCPOption(Option opt)
{
return pseudoTcp.getOption(opt);
}
public void setPTCPOption(Option opt, long optValue)
{
pseudoTcp.setOption(opt, optValue);
}
/** /**
* Start connection procedure * Start connection procedure
@ -250,14 +281,14 @@ public class PseudoTcpSocketImpl
* @param timeout for this operation in ms * @param timeout for this operation in ms
* @throws IOException * @throws IOException
*/ */
public void Connect(InetSocketAddress remoteAddress, long timeout) void doConnect(InetSocketAddress remoteAddress, long timeout)
throws IOException throws IOException
{ {
logger.fine("Connecting to "+remoteAddress); logger.fine("Connecting to "+remoteAddress);
this.remoteAddr = remoteAddress; this.remoteAddr = remoteAddress;
StartThreads(); startThreads();
pseudoTcp.Connect(); pseudoTcp.connect();
UpdateClock(); updateClock();
boolean noTimeout = timeout <= 0; boolean noTimeout = timeout <= 0;
try try
{ {
@ -293,12 +324,12 @@ public class PseudoTcpSocketImpl
* @param timeout for this operation in ms * @param timeout for this operation in ms
* @throws IOException If socket gets closed or timeout expires * @throws IOException If socket gets closed or timeout expires
*/ */
public void Accept(int timeout) void accept(int timeout)
throws IOException throws IOException
{ {
try try
{ {
StartThreads(); startThreads();
PseudoTcpState state = pseudoTcp.getState(); PseudoTcpState state = pseudoTcp.getState();
if (state == PseudoTcpState.TCP_CLOSED) if (state == PseudoTcpState.TCP_CLOSED)
{ {
@ -334,7 +365,7 @@ public class PseudoTcpSocketImpl
{ {
//TODO: not sure how this should work //TODO: not sure how this should work
int timeout = 5000; int timeout = 5000;
Accept(timeout); accept(timeout);
} }
/** /**
@ -349,7 +380,7 @@ public class PseudoTcpSocketImpl
/** /**
* Interrupts clock thread's wait method to force time update * Interrupts clock thread's wait method to force time update
*/ */
private void UpdateClock() private void updateClock()
{ {
synchronized (clock_notify) synchronized (clock_notify)
{ {
@ -360,21 +391,21 @@ public class PseudoTcpSocketImpl
/** /**
* Starts all threads required by the socket * Starts all threads required by the socket
*/ */
private void StartThreads() private void startThreads()
{ {
pseudoTcp.NotifyClock(System.currentTimeMillis()); pseudoTcp.notifyClock(System.currentTimeMillis());
receiveThread = new Thread(new Runnable() receiveThread = new Thread(new Runnable()
{ {
public void run() public void run()
{ {
ReceivePackets(); receivePackets();
} }
}, "PseudoTcpReceiveThread"); }, "PseudoTcpReceiveThread");
clockThread = new Thread(new Runnable() clockThread = new Thread(new Runnable()
{ {
public void run() public void run()
{ {
RunClock(); runClock();
} }
}, "PseudoTcpClockThread"); }, "PseudoTcpClockThread");
runReceive = true; runReceive = true;
@ -384,12 +415,13 @@ public class PseudoTcpSocketImpl
} }
/** /**
* Implements @link(IPseudoTcpNotify) * Implements <tt>PseudoTcpNotify</tt>
* Called when TCP enters connected state. * Called when TCP enters connected state.
* *
* @param tcp * @param tcp
* @see PseudoTcpNotify#onTcpOpen(PseudoTCPBase)
*/ */
public void OnTcpOpen(PseudoTCPBase tcp) public void onTcpOpen(PseudoTCPBase tcp)
{ {
logger.log(Level.FINE, "tcp opened"); logger.log(Level.FINE, "tcp opened");
//Release threads blocked at state_notify monitor object. //Release threads blocked at state_notify monitor object.
@ -398,32 +430,34 @@ public class PseudoTcpSocketImpl
state_notify.notifyAll(); state_notify.notifyAll();
} }
//TCP is considered writeable at this point //TCP is considered writeable at this point
OnTcpWriteable(tcp); onTcpWriteable(tcp);
} }
/** /**
* Implements @link(IPseudoTcpNotify) * Implements <tt>PseudoTcpNotify</tt>
* *
* @param tcp * @param tcp
* @see PseudoTcpNotify#onTcpReadable(PseudoTCPBase)
*/ */
public void OnTcpReadable(PseudoTCPBase tcp) public void onTcpReadable(PseudoTCPBase tcp)
{ {
//release all thread blocked at read_notify monitor //release all thread blocked at read_notify monitor
synchronized (read_notify) synchronized (read_notify)
{ {
logger.log( logger.log(
Level.FINER, Level.FINER,
"TCP READABLE data available for reading: "+tcp.GetAvailable()); "TCP READABLE data available for reading: "+tcp.getAvailable());
read_notify.notifyAll(); read_notify.notifyAll();
} }
} }
/** /**
* Implements @link(IPseudoTcpNotify) * Implements <tt>PseudoTcpNotify</tt>
* *
* @param tcp * @param tcp
* @see PseudoTcpNotify#onTcpWriteable(PseudoTCPBase)
*/ */
public void OnTcpWriteable(PseudoTCPBase tcp) public void onTcpWriteable(PseudoTCPBase tcp)
{ {
logger.log(Level.FINER, "stream writeable"); logger.log(Level.FINER, "stream writeable");
@ -438,12 +472,14 @@ public class PseudoTcpSocketImpl
} }
/** /**
* Implements @link(IPseudoTcpNotify) * Implements <tt>PseudoTcpNotify</tt>
* *
* @param tcp * @param tcp
* @param e * @param e
*
* @see PseudoTcpNotify#onTcpClosed(PseudoTCPBase, IOException)
*/ */
public void OnTcpClosed(PseudoTCPBase tcp, IOException e) public void onTcpClosed(PseudoTCPBase tcp, IOException e)
{ {
if (e != null) if (e != null)
{ {
@ -488,21 +524,23 @@ public class PseudoTcpSocketImpl
* *
* @throws InterruptedException * @throws InterruptedException
*/ */
private void JoinAllThreads() throws InterruptedException private void joinAllThreads() throws InterruptedException
{ {
clockThread.join(); clockThread.join();
receiveThread.join(); receiveThread.join();
} }
/** /**
* Implements @link(IPseudoTcpNotify) * Implements <tt>PseudoTcpNotify</tt>
* *
* @param tcp * @param tcp
* @param buffer * @param buffer
* @param len * @param len
* @return * @return operation result
*
* @see PseudoTcpNotify#tcpWritePacket(PseudoTCPBase, byte[], int)
*/ */
public WriteResult TcpWritePacket(PseudoTCPBase tcp, byte[] buffer, int len) public WriteResult tcpWritePacket(PseudoTCPBase tcp, byte[] buffer, int len)
{ {
if (logger.isLoggable(Level.FINEST)) if (logger.isLoggable(Level.FINEST))
{ {
@ -534,7 +572,7 @@ public class PseudoTcpSocketImpl
/** /**
* Receives packets from the network and passes them to TCP logic class * Receives packets from the network and passes them to TCP logic class
*/ */
private void ReceivePackets() private void receivePackets()
{ {
byte[] buffer = new byte[DATAGRAM_RCV_BUFFER_SIZE]; byte[] buffer = new byte[DATAGRAM_RCV_BUFFER_SIZE];
DatagramPacket packet = new DatagramPacket(buffer, DATAGRAM_RCV_BUFFER_SIZE); DatagramPacket packet = new DatagramPacket(buffer, DATAGRAM_RCV_BUFFER_SIZE);
@ -560,9 +598,9 @@ public class PseudoTcpSocketImpl
} }
synchronized (pseudoTcp) synchronized (pseudoTcp)
{ {
pseudoTcp.NotifyPacket(buffer, packet.getLength()); pseudoTcp.notifyPacket(buffer, packet.getLength());
//we need to update the clock after new packet is receivied //we need to update the clock after new packet is receivied
UpdateClock(); updateClock();
} }
} }
catch (IOException ex) catch (IOException ex)
@ -590,15 +628,15 @@ public class PseudoTcpSocketImpl
* Method runs cyclic notification about time progress for TCP logic class * Method runs cyclic notification about time progress for TCP logic class
* It runs in a separate thread * It runs in a separate thread
*/ */
private void RunClock() private void runClock()
{ {
long sleep; long sleep;
while (runClock) while (runClock)
{ {
synchronized (pseudoTcp) synchronized (pseudoTcp)
{ {
pseudoTcp.NotifyClock(System.currentTimeMillis()); pseudoTcp.notifyClock(System.currentTimeMillis());
sleep = pseudoTcp.GetNextClock(System.currentTimeMillis()); sleep = pseudoTcp.getNextClock(System.currentTimeMillis());
} }
//there might be negative interval even if there's no error //there might be negative interval even if there's no error
@ -682,12 +720,12 @@ public class PseudoTcpSocketImpl
{ {
try try
{ {
pseudoTcp.Close(true); pseudoTcp.close(true);
//System.out.println("ON CLOSE: in flight "+pseudoTcp.GetBytesInFlight()); //System.out.println("ON CLOSE: in flight "+pseudoTcp.GetBytesInFlight());
//System.out.println("ON CLOSE: buff not sent "+pseudoTcp.GetBytesBufferedNotSent()); //System.out.println("ON CLOSE: buff not sent "+pseudoTcp.GetBytesBufferedNotSent());
OnTcpClosed(pseudoTcp, null); onTcpClosed(pseudoTcp, null);
socket.close(); socket.close();
JoinAllThreads(); joinAllThreads();
//UpdateClock(); //UpdateClock();
//TODO: closing procedure //TODO: closing procedure
//Here the thread should be blocked until TCP //Here the thread should be blocked until TCP
@ -719,7 +757,7 @@ public class PseudoTcpSocketImpl
/** /**
* This class implements @link(InputStream) * * This class implements <tt>java.io.InputStream</tt>
*/ */
class PseudoTcpInputStream extends InputStream class PseudoTcpInputStream extends InputStream
{ {
@ -774,7 +812,7 @@ public class PseudoTcpSocketImpl
{ {
synchronized (read_notify) synchronized (read_notify)
{ {
read = pseudoTcp.Recv(buffer, offset, length); read = pseudoTcp.recv(buffer, offset, length);
if (logger.isLoggable(Level.FINER)) if (logger.isLoggable(Level.FINER))
{ {
logger.log(Level.FINER, "Read Recv read count: " + read); logger.log(Level.FINER, "Read Recv read count: " + read);
@ -788,7 +826,7 @@ public class PseudoTcpSocketImpl
if (logger.isLoggable(Level.FINER)) if (logger.isLoggable(Level.FINER))
{ {
logger.log(Level.FINER, logger.log(Level.FINER,
"Read notified: " + pseudoTcp.GetAvailable()); "Read notified: " + pseudoTcp.getAvailable());
} }
} }
if (exception != null) if (exception != null)
@ -813,7 +851,7 @@ public class PseudoTcpSocketImpl
@Override @Override
public int available() throws IOException public int available() throws IOException
{ {
return pseudoTcp.GetAvailable(); return pseudoTcp.getAvailable();
} }
@Override @Override
@ -823,7 +861,7 @@ public class PseudoTcpSocketImpl
} }
/** /**
* Implements @link(OutputStream) * Implements <tt>java.io.OutputStream</tt>
*/ */
class PseudoTcpOutputStream extends OutputStream class PseudoTcpOutputStream extends OutputStream
{ {
@ -859,7 +897,7 @@ public class PseudoTcpSocketImpl
{ {
synchronized (pseudoTcp) synchronized (pseudoTcp)
{ {
sent = pseudoTcp.Send(buffer, offset + length - toSend, toSend); sent = pseudoTcp.send(buffer, offset + length - toSend, toSend);
} }
if (sent > 0) if (sent > 0)
{ {
@ -876,7 +914,7 @@ public class PseudoTcpSocketImpl
} }
logger.log(Level.FINER, logger.log(Level.FINER,
"Write notified, available: " "Write notified, available: "
+ pseudoTcp.GetAvailableSendBuffer()); + pseudoTcp.getAvailableSendBuffer());
if (exception != null) if (exception != null)
{ {
throw exception; throw exception;
@ -906,8 +944,8 @@ public class PseudoTcpSocketImpl
public synchronized void flush() throws IOException public synchronized void flush() throws IOException
{ {
logger.log(Level.FINE, "Flushing..."); logger.log(Level.FINE, "Flushing...");
final Object ackNotify = pseudoTcp.GetAckNotify(); final Object ackNotify = pseudoTcp.getAckNotify();
while (pseudoTcp.GetBytesBufferedNotSent() > 0) while (pseudoTcp.getBytesBufferedNotSent() > 0)
{ {
synchronized (ackNotify) synchronized (ackNotify)
{ {

View File

@ -0,0 +1,25 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the Jitsi community (https://jitsi.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.pseudotcp;
/**
* Class used internally as a structure for receive segments
*
* @author Pawel
*/
class RSegment
{
public long seq, len;
public RSegment(long seq, long len)
{
this.seq = seq;
this.len = len;
}
}

View File

@ -0,0 +1,29 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the Jitsi community (https://jitsi.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.pseudotcp;
/**
* Class used internally as a structure for send segments
*
* @author Pawel Domas
*/
class SSegment
{
long seq, len;
//uint32 tstamp;
short xmit;
boolean bCtrl;
SSegment(long s, long l, boolean c)
{
seq = s;
len = l;
xmit = 0;
bCtrl = c;
}
}

View File

@ -0,0 +1,27 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the Jitsi community (https://jitsi.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.pseudotcp;
/**
* Class used as a segment structure
*
* @author Pawel Domas
*/
public class Segment
{
long conv;
long seq;
long ack;
byte flags;
int wnd;
long tsval;
long tsecr;
byte[] data;
int len;
}

View File

@ -0,0 +1,18 @@
/*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* Maintained by the Jitsi community (https://jitsi.org).
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.ice4j.pseudotcp;
/**
* Send flags used internally
*
* @author Pawel Domas
*/
enum SendFlags
{
sfNone, sfImmediateAck, sfDelayedAck;
}

View File

@ -46,33 +46,33 @@ public class ByteFifoBuffer
/** /**
* @return buffer's capacity * @return buffer's capacity
*/ */
public int Length() public int length()
{ {
return array.length; return array.length;
} }
/** /**
* Method reads <tt>count</tt> bytes into <tt>out_buffer</tt> * Method reads <tt>count</tt> bytes into <tt>out_buffer</tt>.
* Current read position is incremented by count of bytes * Current read position is incremented by count of bytes
* that has been successfully read * that has been successfully read.
* *
* @param out_buffer * @param out_buffer
* @param count * @param count
* @return bytes successfully read * @return bytes successfully read
*/ */
public int Read(byte[] out_buffer, int count) public int read(byte[] out_buffer, int count)
{ {
return Read(out_buffer, 0, count); return read(out_buffer, 0, count);
} }
/** /**
* Read with buffer offset * Read with buffer offset
* @param out_buffer * @param out_buffer
* @param buff_offset * @param buff_offset
* @param len * @param count bytes to read
* @return * @return read byte count
*/ */
public int Read(byte[] out_buffer, int buff_offset, int count) { public int read(byte[] out_buffer, int buff_offset, int count) {
count = readLimit(count); count = readLimit(count);
if (count > 0) if (count > 0)
{ {
@ -127,7 +127,7 @@ public class ByteFifoBuffer
* *
* @return space left in buffer for write * @return space left in buffer for write
*/ */
public int GetWriteRemaining() public int getWriteRemaining()
{ {
return array.length - buffered; return array.length - buffered;
} }
@ -136,7 +136,7 @@ public class ByteFifoBuffer
* *
* @return bytes stored in buffer and available for reading * @return bytes stored in buffer and available for reading
*/ */
public int GetBuffered() public int getBuffered()
{ {
return buffered; return buffered;
} }
@ -148,9 +148,9 @@ public class ByteFifoBuffer
* @param count * @param count
* @return bytes successfully written to buffer * @return bytes successfully written to buffer
*/ */
public int Write(byte[] buffer, int count) public int write(byte[] buffer, int count)
{ {
return Write(buffer, 0, count); return write(buffer, 0, count);
} }
/** /**
@ -160,7 +160,7 @@ public class ByteFifoBuffer
* @param count * @param count
* @return byte count actually read * @return byte count actually read
*/ */
public int Write(byte[] data, int offset, int count) public int write(byte[] data, int offset, int count)
{ {
/* /*
* System.out.println("----write " + this + " " + len + " buffered " + * System.out.println("----write " + this + " " + len + " buffered " +
@ -233,7 +233,7 @@ public class ByteFifoBuffer
throws IllegalArgumentException throws IllegalArgumentException
{ {
int spaceReq; int spaceReq;
int availSpace = GetWriteRemaining(); int availSpace = getWriteRemaining();
if (newWrPos < write_pos) if (newWrPos < write_pos)
{ {
spaceReq = newWrPos + (array.length - write_pos); spaceReq = newWrPos + (array.length - write_pos);
@ -254,11 +254,11 @@ public class ByteFifoBuffer
* *
* @param count * @param count
*/ */
public void ConsumeWriteBuffer(int count) public void consumeWriteBuffer(int count)
throws IllegalArgumentException, throws IllegalArgumentException,
BufferOverflowException BufferOverflowException
{ {
if (count > GetWriteRemaining()) if (count > getWriteRemaining())
{ {
throw new BufferOverflowException(); throw new BufferOverflowException();
} }
@ -280,9 +280,9 @@ public class ByteFifoBuffer
* @return <tt>true</tt> if operation is possible to perform, that is if new * @return <tt>true</tt> if operation is possible to perform, that is if new
* buffered data fits into new buffer * buffered data fits into new buffer
*/ */
public boolean SetCapacity(int new_size) public boolean setCapacity(int new_size)
{ {
if (new_size < GetBuffered()) if (new_size < getBuffered())
{ {
return false; return false;
} }
@ -299,7 +299,7 @@ public class ByteFifoBuffer
* @throws BufferUnderflowException if new position exceeds buffered data * @throws BufferUnderflowException if new position exceeds buffered data
* count * count
*/ */
public void ConsumeReadData(int count) public void consumeReadData(int count)
throws IllegalArgumentException, throws IllegalArgumentException,
BufferUnderflowException BufferUnderflowException
{ {
@ -328,7 +328,7 @@ public class ByteFifoBuffer
* @param offset from current read position * @param offset from current read position
* @return bytes successfully read * @return bytes successfully read
*/ */
public int ReadOffset(byte[] dst_buff, public int readOffset(byte[] dst_buff,
int dst_buff_offset, int dst_buff_offset,
int count, int count,
int offset) int offset)
@ -353,10 +353,10 @@ public class ByteFifoBuffer
* @param nOffset from buffer's write position * @param nOffset from buffer's write position
* @return bytes successfully written * @return bytes successfully written
*/ */
public int WriteOffset(byte[] data, int count, int nOffset) public int writeOffset(byte[] data, int count, int nOffset)
throws BufferOverflowException throws BufferOverflowException
{ {
if (count > GetWriteRemaining()) if (count > getWriteRemaining())
{ {
throw new BufferOverflowException(); throw new BufferOverflowException();
} }
@ -366,25 +366,18 @@ public class ByteFifoBuffer
} }
int offWritePos = (this.write_pos + nOffset) % array.length; int offWritePos = (this.write_pos + nOffset) % array.length;
count = writeLimit(count); count = writeLimit(count);
//try{
assertWriteLimit(offWritePos + count); assertWriteLimit(offWritePos + count);
//}catch(IllegalArgumentException e){
// System.out.println("Write offset: " + nOffset + " count: " + count
//+ " wpos: " + write_pos + " buffered: " + buffered + " len: " + length + this);
// throw e;
//}
//buffer.position(writePos + nOffset);
writeOp(data, 0, count, array, offWritePos, array.length); writeOp(data, 0, count, array, offWritePos, array.length);
//buffer.position(writePos);
return count; return count;
} }
public void ResetReadPosition() public void resetReadPosition()
{ {
this.read_pos = 0; this.read_pos = 0;
} }
public void ResetWritePosition() public void resetWritePosition()
{ {
this.write_pos = 0; this.write_pos = 0;
this.buffered = 0; this.buffered = 0;

View File

@ -41,12 +41,12 @@ public class MultiThreadSupportTest
} }
private long assertWaitInterval = 100; private long assertWaitInterval = 100;
protected interface IWaitUntilDone protected interface WaitUntilDone
{ {
public boolean isDone(); public boolean isDone();
} }
protected boolean assert_wait_until(IWaitUntilDone wait, long timeoutMs) protected boolean assert_wait_until(WaitUntilDone wait, long timeoutMs)
{ {
try try
{ {

View File

@ -34,12 +34,14 @@ public class PseudoTcpStreamTest
* Test one-way transfer with @link(PseudoTcpStream) * Test one-way transfer with @link(PseudoTcpStream)
* *
* @throws SocketException * @throws SocketException
* @throws UnknownHostException
*/ */
public void testConnectTransferClose() throws SocketException public void testConnectTransferClose()
throws SocketException,
UnknownHostException
{ {
Thread.setDefaultUncaughtExceptionHandler(this); Thread.setDefaultUncaughtExceptionHandler(this);
final int server_port = 49999; final int server_port = 49999;
long conv_id = 0;
int transferTimeout = 5000; int transferTimeout = 5000;
// bytes that will be read as a single byte // bytes that will be read as a single byte
@ -48,12 +50,10 @@ public class PseudoTcpStreamTest
PseudoTcpTestBase.createDummyData(singleStepCount); PseudoTcpTestBase.createDummyData(singleStepCount);
final int sizeA = 138746; final int sizeA = 138746;
final byte[] bufferA = PseudoTcpTestBase.createDummyData(sizeA); final byte[] bufferA = PseudoTcpTestBase.createDummyData(sizeA);
final int sizeB = 483746; final int sizeB = 4803746;
final byte[] bufferB = PseudoTcpTestBase.createDummyData(sizeB); final byte[] bufferB = PseudoTcpTestBase.createDummyData(sizeB);
final InetSocketAddress serverAddress =
final PseudoTcpSocketImpl server = new PseudoTcpSocketImpl(conv_id); new InetSocketAddress(InetAddress.getLocalHost(), server_port);
final PseudoTcpSocketImpl client = new PseudoTcpSocketImpl(conv_id);
Thread serverThread = new Thread(new Runnable() Thread serverThread = new Thread(new Runnable()
{ {
@Override @Override
@ -61,8 +61,12 @@ public class PseudoTcpStreamTest
{ {
try try
{ {
server.bind(InetAddress.getLocalHost(), server_port); final PseudoTcpSocket server =
server.accept(null); new PseudoTcpSocketFactory().
createSocket();
server.setDebugName("L");
server.bind(serverAddress);
server.accept(5000);
byte[] rcvdSingle = new byte[singleStepCount]; byte[] rcvdSingle = new byte[singleStepCount];
// read by one byte // read by one byte
for (int i = 0; i < singleStepCount; i++) for (int i = 0; i < singleStepCount; i++)
@ -76,7 +80,7 @@ public class PseudoTcpStreamTest
byte[] recvdBufferB = byte[] recvdBufferB =
receiveBuffer(server.getInputStream(), sizeB); receiveBuffer(server.getInputStream(), sizeB);
assertArrayEquals(bufferB, recvdBufferB); assertArrayEquals(bufferB, recvdBufferB);
// server.Close(); // server.close();
} }
catch (IOException ex) catch (IOException ex)
{ {
@ -85,16 +89,17 @@ public class PseudoTcpStreamTest
} }
}); });
final PseudoTcpSocket client =
new PseudoTcpSocketFactory().createSocket();
Thread clientThread = new Thread(new Runnable() Thread clientThread = new Thread(new Runnable()
{ {
@Override @Override
public void run() public void run()
{ {
try try
{ {
client.connect(InetAddress.getLocalHost(), server_port); client.setDebugName("R");
assertEquals(PseudoTcpState.TCP_ESTABLISHED, client.connect(serverAddress, 5000);
client.getState());
// write single array // write single array
for (int i = 0; i < singleStepCount; i++) for (int i = 0; i < singleStepCount; i++)
client.getOutputStream().write(bufferSingle[i]); client.getOutputStream().write(bufferSingle[i]);
@ -134,7 +139,7 @@ public class PseudoTcpStreamTest
clientThread.start(); clientThread.start();
try try
{ {
boolean success = assert_wait_until(new IWaitUntilDone() boolean success = assert_wait_until(new WaitUntilDone()
{ {
@Override @Override
public boolean isDone() public boolean isDone()
@ -184,7 +189,7 @@ public class PseudoTcpStreamTest
try try
{ {
PseudoTcpSocketImpl server = new PseudoTcpSocketImpl(0); PseudoTcpSocketImpl server = new PseudoTcpSocketImpl(0);
server.Accept(10); server.accept(10);
fail("Should throw timeout exception"); fail("Should throw timeout exception");
} }
catch (IOException ex) catch (IOException ex)

View File

@ -21,7 +21,7 @@ import org.ice4j.pseudotcp.util.*;
* @author Pawel Domas * @author Pawel Domas
*/ */
public abstract class PseudoTcpTestBase extends MultiThreadSupportTest public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
implements IPseudoTcpNotify implements PseudoTcpNotify
{ {
/** /**
* The logger. * The logger.
@ -77,8 +77,8 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
remoteTcp.debugName = "REM"; remoteTcp.debugName = "REM";
this.localTcp = new PseudoTCPBase(this, 1); this.localTcp = new PseudoTCPBase(this, 1);
localTcp.debugName = "LOC"; localTcp.debugName = "LOC";
SetLocalMtu(65535); setLocalMtu(65535);
SetRemoteMtu(65535); setRemoteMtu(65535);
} }
/** /**
@ -100,9 +100,9 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* *
* @param mtu * @param mtu
*/ */
void SetLocalMtu(int mtu) void setLocalMtu(int mtu)
{ {
localTcp.NotifyMTU(mtu); localTcp.notifyMTU(mtu);
local_mtu_ = mtu; local_mtu_ = mtu;
} }
@ -111,9 +111,9 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* *
* @param mtu * @param mtu
*/ */
void SetRemoteMtu(int mtu) void setRemoteMtu(int mtu)
{ {
remoteTcp.NotifyMTU(mtu); remoteTcp.notifyMTU(mtu);
remote_mtu_ = mtu; remote_mtu_ = mtu;
} }
@ -122,7 +122,7 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* *
* @param delay * @param delay
*/ */
void SetDelay(int delay) void setDelay(int delay)
{ {
delay_ = delay; delay_ = delay;
} }
@ -132,7 +132,7 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* *
* @param percent * @param percent
*/ */
void SetLoss(int percent) void setLoss(int percent)
{ {
loss_ = percent; loss_ = percent;
} }
@ -142,10 +142,10 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* *
* @param enable_nagles * @param enable_nagles
*/ */
void SetOptNagling(boolean enable_nagles) void setOptNagling(boolean enable_nagles)
{ {
localTcp.SetOption(Option.OPT_NODELAY, enable_nagles ? 0 : 1); localTcp.setOption(Option.OPT_NODELAY, enable_nagles ? 0 : 1);
remoteTcp.SetOption(Option.OPT_NODELAY, enable_nagles ? 0 : 1); remoteTcp.setOption(Option.OPT_NODELAY, enable_nagles ? 0 : 1);
} }
@ -154,10 +154,10 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* *
* @param ack_delay * @param ack_delay
*/ */
void SetOptAckDelay(int ack_delay) void setOptAckDelay(int ack_delay)
{ {
localTcp.SetOption(Option.OPT_ACKDELAY, ack_delay); localTcp.setOption(Option.OPT_ACKDELAY, ack_delay);
remoteTcp.SetOption(Option.OPT_ACKDELAY, ack_delay); remoteTcp.setOption(Option.OPT_ACKDELAY, ack_delay);
} }
/** /**
@ -165,10 +165,10 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* *
* @param size * @param size
*/ */
void SetOptSndBuf(int size) void setOptSndBuf(int size)
{ {
localTcp.SetOption(Option.OPT_SNDBUF, size); localTcp.setOption(Option.OPT_SNDBUF, size);
remoteTcp.SetOption(Option.OPT_SNDBUF, size); remoteTcp.setOption(Option.OPT_SNDBUF, size);
} }
/** /**
@ -176,9 +176,9 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* *
* @param size * @param size
*/ */
void SetRemoteOptRcvBuf(int size) void setRemoteOptRcvBuf(int size)
{ {
remoteTcp.SetOption(Option.OPT_RCVBUF, size); remoteTcp.setOption(Option.OPT_RCVBUF, size);
} }
/** /**
@ -186,15 +186,15 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* *
* @param size * @param size
*/ */
void SetLocalOptRcvBuf(int size) void setLocalOptRcvBuf(int size)
{ {
localTcp.SetOption(Option.OPT_RCVBUF, size); localTcp.setOption(Option.OPT_RCVBUF, size);
} }
/** /**
* Disable window scaling for remote peer * Disable window scaling for remote peer
*/ */
void DisableRemoteWindowScale() void disableRemoteWindowScale()
{ {
remoteTcp.disableWindowScale(); remoteTcp.disableWindowScale();
} }
@ -202,7 +202,7 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
/** /**
* Disable window scaling for local peer * Disable window scaling for local peer
*/ */
void DisableLocalWindowScale() void disableLocalWindowScale()
{ {
localTcp.disableWindowScale(); localTcp.disableWindowScale();
} }
@ -212,19 +212,19 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* *
* @throws IOException * @throws IOException
*/ */
void Connect() throws IOException void connect() throws IOException
{ {
localTcp.Connect(); localTcp.connect();
UpdateLocalClock(); updateLocalClock();
} }
/** /**
* Closes the connection * Closes the connection
*/ */
void Close() void close()
{ {
localTcp.Close(false); localTcp.close(false);
UpdateLocalClock(); updateLocalClock();
} }
/** /**
@ -234,12 +234,12 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* @param tcp * @param tcp
*/ */
@Override @Override
public void OnTcpOpen(PseudoTCPBase tcp) public void onTcpOpen(PseudoTCPBase tcp)
{ {
if (tcp == localTcp) if (tcp == localTcp)
{ {
have_connected_ = true; have_connected_ = true;
OnTcpWriteable(tcp); onTcpWriteable(tcp);
} }
} }
@ -250,7 +250,7 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* @param exc * @param exc
*/ */
@Override @Override
public void OnTcpClosed(PseudoTCPBase tcp, IOException exc) public void onTcpClosed(PseudoTCPBase tcp, IOException exc)
{ {
assert exc == null; assert exc == null;
if (tcp == remoteTcp) if (tcp == remoteTcp)
@ -263,7 +263,7 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
*/ */
private Random random = new Random(); private Random random = new Random();
int RandomInt() int randomInt()
{ {
return random.nextInt(100); return random.nextInt(100);
} }
@ -276,9 +276,9 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* @return * @return
* @throws IOException * @throws IOException
*/ */
int LocalSend(byte[] data, int len) throws IOException int localSend(byte[] data, int len) throws IOException
{ {
return localTcp.Send(data, len); return localTcp.send(data, len);
} }
/** /**
@ -289,9 +289,9 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* @return * @return
* @throws IOException * @throws IOException
*/ */
int LocalRecv(byte[] buffer, int len) throws IOException int localRecv(byte[] buffer, int len) throws IOException
{ {
return localTcp.Recv(buffer, len); return localTcp.recv(buffer, len);
} }
/** /**
@ -302,10 +302,10 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* @return * @return
* @throws IOException * @throws IOException
*/ */
int RemoteRecv(byte[] buffer, int len) throws IOException int remoteRecv(byte[] buffer, int len) throws IOException
{ {
return remoteTcp.Recv(buffer, len); return remoteTcp.recv(buffer, len);
} }
/** /**
@ -316,10 +316,10 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* @return * @return
* @throws IOException * @throws IOException
*/ */
int RemoteSend(byte[] data, int len) int remoteSend(byte[] data, int len)
throws IOException throws IOException
{ {
return remoteTcp.Send(data, len); return remoteTcp.send(data, len);
} }
/** /**
@ -329,11 +329,11 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* @param len * @param len
* @throws IOException * @throws IOException
*/ */
private void LocalPacket(byte[] data, int len) private void localPacket(byte[] data, int len)
throws IOException throws IOException
{ {
localTcp.NotifyPacket(data, len); localTcp.notifyPacket(data, len);
UpdateLocalClock(); updateLocalClock();
} }
/** /**
@ -343,11 +343,11 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* @param len * @param len
* @throws IOException * @throws IOException
*/ */
private void RemotePacket(byte[] data, int len) private void remotePacket(byte[] data, int len)
throws IOException throws IOException
{ {
remoteTcp.NotifyPacket(data, len); remoteTcp.notifyPacket(data, len);
UpdateRemoteClock(); updateRemoteClock();
} }
/** /**
@ -366,7 +366,7 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
{ {
try try
{ {
RemotePacket(data, len); remotePacket(data, len);
} }
catch (IOException ex) catch (IOException ex)
{ {
@ -392,7 +392,7 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
{ {
try try
{ {
LocalPacket(data, len); localPacket(data, len);
} }
catch (IOException ex) catch (IOException ex)
{ {
@ -412,11 +412,11 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* @return * @return
*/ */
@Override @Override
public WriteResult TcpWritePacket(PseudoTCPBase tcp, byte[] buffer, int len) public WriteResult tcpWritePacket(PseudoTCPBase tcp, byte[] buffer, int len)
{ {
// Randomly drop the desired percentage of packets. // Randomly drop the desired percentage of packets.
// Also drop packets that are larger than the configured MTU. // Also drop packets that are larger than the configured MTU.
if (RandomInt() < loss_) if (randomInt() < loss_)
{ {
if (logger.isLoggable(Level.FINE)) if (logger.isLoggable(Level.FINE))
{ {
@ -452,7 +452,7 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
/** /**
* Wakes up local clock thread from wait method causing forced time update * Wakes up local clock thread from wait method causing forced time update
*/ */
protected void UpdateLocalClock() protected void updateLocalClock()
{ {
if (localClockThread != null) if (localClockThread != null)
{ {
@ -466,7 +466,7 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
/** /**
* Wakes up remote clock thread from wait method causing forced time update * Wakes up remote clock thread from wait method causing forced time update
*/ */
protected void UpdateRemoteClock() protected void updateRemoteClock()
{ {
if (remoteClockThread != null) if (remoteClockThread != null)
{ {
@ -483,22 +483,22 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* @param tcp * @param tcp
* @param lock * @param lock
*/ */
private void UpdateNextClock(final PseudoTCPBase tcp, final Object lock) private void updateNextClock(final PseudoTCPBase tcp, final Object lock)
{ {
try try
{ {
long now = PseudoTCPBase.Now(); long now = PseudoTCPBase.now();
//System.out.println(tcp.debugName + " NOTIFY CLOCK: " + now); //System.out.println(tcp.debugName + " NOTIFY CLOCK: " + now);
synchronized (tcp) synchronized (tcp)
{ {
tcp.NotifyClock(now); tcp.notifyClock(now);
} }
//UpdateClock(tcp); //UpdateClock(tcp);
long interval; // NOLINT long interval; // NOLINT
synchronized (tcp) synchronized (tcp)
{ {
interval = tcp.GetNextClock(PseudoTCPBase.Now()); interval = tcp.getNextClock(PseudoTCPBase.now());
} }
//interval = Math.max(interval, 0L); // sometimes interval is < 0 //interval = Math.max(interval, 0L); // sometimes interval is < 0
if (logger.isLoggable(Level.FINEST)) if (logger.isLoggable(Level.FINEST))
@ -545,7 +545,7 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
/** /**
* Start clock threads * Start clock threads
*/ */
protected void StartClocks() protected void startClocks()
{ {
if (localClockThread == null && remoteClockThread == null) if (localClockThread == null && remoteClockThread == null)
{ {
@ -558,7 +558,7 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
while (runClocks) while (runClocks)
{ {
//localTcp.NotifyClock(PseudoTCPBase.Now()); //localTcp.NotifyClock(PseudoTCPBase.Now());
UpdateNextClock(localTcp, localClockLock); updateNextClock(localTcp, localClockLock);
} }
@ -572,7 +572,7 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
while (runClocks) while (runClocks)
{ {
//remoteTcp.NotifyClock(PseudoTCPBase.Now()); //remoteTcp.NotifyClock(PseudoTCPBase.Now());
UpdateNextClock(remoteTcp, remoteClockLock); updateNextClock(remoteTcp, remoteClockLock);
} }
} }
@ -589,7 +589,7 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
/** /**
* Stops clock threads * Stops clock threads
*/ */
protected void StopClocks() protected void stopClocks()
{ {
if (localClockThread != null && remoteClockThread != null) if (localClockThread != null && remoteClockThread != null)
{ {
@ -623,7 +623,7 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
*/ */
protected boolean assert_Connected_wait(int kConnectTimeoutMs) protected boolean assert_Connected_wait(int kConnectTimeoutMs)
{ {
return assert_wait_until(new IWaitUntilDone() return assert_wait_until(new WaitUntilDone()
{ {
@Override @Override
public boolean isDone() public boolean isDone()
@ -642,7 +642,7 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
*/ */
protected boolean assert_Disconnected_wait(long kTransferTimeoutMs) protected boolean assert_Disconnected_wait(long kTransferTimeoutMs)
{ {
return assert_wait_until(new IWaitUntilDone() return assert_wait_until(new WaitUntilDone()
{ {
@Override @Override
public boolean isDone() public boolean isDone()
@ -676,7 +676,7 @@ public abstract class PseudoTcpTestBase extends MultiThreadSupportTest
* @param kBps * @param kBps
* @return timeout for transfer in ms(minimum 3000 ms) * @return timeout for transfer in ms(minimum 3000 ms)
*/ */
public long MaxTransferTime(long size, long kBps) public long maxTransferTime(long size, long kBps)
{ {
long transferTout = ((size) / kBps) * 8 * 1000; long transferTout = ((size) / kBps) * 8 * 1000;
return transferTout > 3000 ? transferTout : 3000; return transferTout > 3000 ? transferTout : 3000;

View File

@ -66,7 +66,7 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
* @param size * @param size
* @param iterations * @param iterations
*/ */
public void TestPingPong(int size, int iterations) public void doTestPingPong(int size, int iterations)
{ {
Thread.setDefaultUncaughtExceptionHandler(this); Thread.setDefaultUncaughtExceptionHandler(this);
long start, end; long start, end;
@ -76,15 +76,15 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
// Create some dummy data // Create some dummy data
byte[] dummy = createDummyData(size); byte[] dummy = createDummyData(size);
send_stream = new ByteFifoBuffer(size); send_stream = new ByteFifoBuffer(size);
send_stream.Write(dummy, size); send_stream.write(dummy, size);
//Prepare the receive stream //Prepare the receive stream
recv_stream = new ByteFifoBuffer(size); recv_stream = new ByteFifoBuffer(size);
//Connect and wait until connected //Connect and wait until connected
start = PseudoTCPBase.Now(); start = PseudoTCPBase.now();
StartClocks(); startClocks();
try try
{ {
Connect(); connect();
} }
catch (IOException ex) catch (IOException ex)
{ {
@ -96,8 +96,8 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
// Sending will start from OnTcpWriteable and stop when the required // Sending will start from OnTcpWriteable and stop when the required
// number of iterations have completed. // number of iterations have completed.
assert_Disconnected_wait(kMinTransferRate); assert_Disconnected_wait(kMinTransferRate);
long elapsed = PseudoTCPBase.Now() - start; long elapsed = PseudoTCPBase.now() - start;
StopClocks(); stopClocks();
logger.log(Level.INFO, logger.log(Level.INFO,
"Performed " + iterations + " pings in " + elapsed + " ms"); "Performed " + iterations + " pings in " + elapsed + " ms");
} }
@ -108,13 +108,13 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
* @param tcp * @param tcp
*/ */
@Override @Override
public void OnTcpReadable(PseudoTCPBase tcp) public void onTcpReadable(PseudoTCPBase tcp)
{ {
assertEquals("Unexpected onTcpReadable", receiver, tcp); assertEquals("Unexpected onTcpReadable", receiver, tcp);
try try
{ {
// Stream bytes to the recv stream as they arrive. // Stream bytes to the recv stream as they arrive.
ReadData(); readData();
} }
catch (IOException ex) catch (IOException ex)
{ {
@ -123,8 +123,8 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
} }
// If we've received the desired amount of data, rewind things // If we've received the desired amount of data, rewind things
// and send it back the other way! // and send it back the other way!
int recvd = recv_stream.GetBuffered(); int recvd = recv_stream.getBuffered();
int required = send_stream.Length(); int required = send_stream.length();
if (logger.isLoggable(Level.FINER)) if (logger.isLoggable(Level.FINER))
{ {
logger.log(Level.FINER, logger.log(Level.FINER,
@ -135,19 +135,19 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
{ {
if (receiver == getLocalTcp() && --iterationsRemaining == 0) if (receiver == getLocalTcp() && --iterationsRemaining == 0)
{ {
Close(); close();
// TODO: Fake OnTcpClosed() on the receiver for now. // TODO: Fake OnTcpClosed() on the receiver for now.
OnTcpClosed(getRemoteTcp(), null); onTcpClosed(getRemoteTcp(), null);
return; return;
} }
//switches receivier with sender and performs test the other way //switches receivier with sender and performs test the other way
PseudoTCPBase tmp = receiver; PseudoTCPBase tmp = receiver;
receiver = sender; receiver = sender;
sender = tmp; sender = tmp;
send_stream.ResetReadPosition(); send_stream.resetReadPosition();
send_stream.ConsumeWriteBuffer(send_stream.GetWriteRemaining()); send_stream.consumeWriteBuffer(send_stream.getWriteRemaining());
recv_stream.ResetWritePosition(); recv_stream.resetWritePosition();
OnTcpWriteable(sender); onTcpWriteable(sender);
} }
} }
@ -158,7 +158,7 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
* @param tcp * @param tcp
*/ */
@Override @Override
public void OnTcpWriteable(PseudoTCPBase tcp) public void onTcpWriteable(PseudoTCPBase tcp)
{ {
if (tcp != sender) if (tcp != sender)
{ {
@ -169,7 +169,7 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
logger.log(Level.FINER, "Flow Control Lifted"); logger.log(Level.FINER, "Flow Control Lifted");
try try
{ {
WriteData(); writeData();
} }
catch (IOException ex) catch (IOException ex)
{ {
@ -183,20 +183,20 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
* *
* @throws IOException * @throws IOException
*/ */
private void ReadData() throws IOException private void readData() throws IOException
{ {
byte[] block = new byte[kBlockSize]; byte[] block = new byte[kBlockSize];
int rcvd = 0; int rcvd = 0;
do do
{ {
rcvd = receiver.Recv(block, block.length); rcvd = receiver.recv(block, block.length);
if (rcvd > 0) if (rcvd > 0)
{ {
recv_stream.Write(block, rcvd); recv_stream.write(block, rcvd);
if (logger.isLoggable(Level.FINE)) if (logger.isLoggable(Level.FINE))
{ {
logger.log(Level.FINE, logger.log(Level.FINE,
"Receivied: " + recv_stream.GetBuffered()); "Receivied: " + recv_stream.getBuffered());
} }
} }
} }
@ -208,7 +208,7 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
* *
* @throws IOException * @throws IOException
*/ */
private void WriteData() throws IOException private void writeData() throws IOException
{ {
int tosend; int tosend;
int sent = 0; int sent = 0;
@ -216,11 +216,11 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
do do
{ {
tosend = bytesPerSend != 0 ? bytesPerSend : block.length; tosend = bytesPerSend != 0 ? bytesPerSend : block.length;
tosend = send_stream.Read(block, tosend); tosend = send_stream.read(block, tosend);
if (tosend > 0) if (tosend > 0)
{ {
sent = sender.Send(block, tosend); sent = sender.send(block, tosend);
UpdateLocalClock(); updateLocalClock();
if (sent != -1) if (sent != -1)
{ {
if(logger.isLoggable(Level.FINE)) if(logger.isLoggable(Level.FINE))
@ -253,9 +253,9 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test ping - pong 1xMTU"); //logger.log(Level.INFO, "Test ping - pong 1xMTU");
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong(); PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.TestPingPong(100, 100); test.doTestPingPong(100, 100);
} }
/** /**
@ -265,9 +265,9 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test ping - pong 3xMTU"); //logger.log(Level.INFO, "Test ping - pong 3xMTU");
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong(); PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.TestPingPong(400, 100); test.doTestPingPong(400, 100);
} }
/** /**
@ -278,9 +278,9 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test ping - pong 2xMTU"); //logger.log(Level.INFO, "Test ping - pong 2xMTU");
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong(); PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.TestPingPong(2000, 5); test.doTestPingPong(2000, 5);
} }
/** /**
@ -291,10 +291,10 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test ping - pong 2xMTU ack delay off"); //logger.log(Level.INFO, "Test ping - pong 2xMTU ack delay off");
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong(); PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetOptAckDelay(0); test.setOptAckDelay(0);
test.TestPingPong(2000, 100); test.doTestPingPong(2000, 100);
} }
/** /**
@ -305,10 +305,10 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test ping - pong 2xMTU nagling off"); //logger.log(Level.INFO, "Test ping - pong 2xMTU nagling off");
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong(); PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetOptNagling(false); test.setOptNagling(false);
test.TestPingPong(2000, 5); test.doTestPingPong(2000, 5);
} }
/** /**
@ -319,11 +319,11 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test ping - pong short segments"); //logger.log(Level.INFO, "Test ping - pong short segments");
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong(); PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetOptAckDelay(5000); test.setOptAckDelay(5000);
test.setBytesPerSend(50); // i.e. two Send calls per payload test.setBytesPerSend(50); // i.e. two Send calls per payload
test.TestPingPong(100, 5); test.doTestPingPong(100, 5);
} }
/** /**
@ -334,11 +334,11 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test ping - pong short segments nagling off"); //logger.log(Level.INFO, "Test ping - pong short segments nagling off");
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong(); PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetOptNagling(false); test.setOptNagling(false);
test.setBytesPerSend(50); // i.e. two Send calls per payload test.setBytesPerSend(50); // i.e. two Send calls per payload
test.TestPingPong(100, 5); test.doTestPingPong(100, 5);
} }
/** /**
@ -349,10 +349,10 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test ping - pong short segments nagling off"); //logger.log(Level.INFO, "Test ping - pong short segments nagling off");
PseudoTcpTestPingPong test = new PseudoTcpTestPingPong(); PseudoTcpTestPingPong test = new PseudoTcpTestPingPong();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.setBytesPerSend(50); // i.e. two Send calls per payload test.setBytesPerSend(50); // i.e. two Send calls per payload
test.SetOptAckDelay(0); test.setOptAckDelay(0);
test.TestPingPong(100, 5); test.doTestPingPong(100, 5);
} }
} }

View File

@ -53,7 +53,7 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
*/ */
private int testDataSize; private int testDataSize;
public void TestTransfer(int size) public void doTestTransfer(int size)
{ {
Thread.setDefaultUncaughtExceptionHandler(this); Thread.setDefaultUncaughtExceptionHandler(this);
testDataSize = size; testDataSize = size;
@ -63,15 +63,15 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
// Create some dummy data // Create some dummy data
byte[] dummy = createDummyData(size); byte[] dummy = createDummyData(size);
send_stream = new ByteFifoBuffer(size); send_stream = new ByteFifoBuffer(size);
send_stream.Write(dummy, size); send_stream.write(dummy, size);
//Prepare the receive stream //Prepare the receive stream
recv_stream = new ByteFifoBuffer(size); recv_stream = new ByteFifoBuffer(size);
//Connect and wait until connected //Connect and wait until connected
start = PseudoTCPBase.Now(); start = PseudoTCPBase.now();
StartClocks(); startClocks();
try try
{ {
Connect(); connect();
} }
catch (IOException ex) catch (IOException ex)
{ {
@ -82,13 +82,13 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
// Connect and wait until connected. // Connect and wait until connected.
assert_Connected_wait(kConnectTimeoutMs); assert_Connected_wait(kConnectTimeoutMs);
ScheduleWriteAction(0); scheduleWriteAction(0);
long transferTout = MaxTransferTime(dummy.length, kMinTransferRate); long transferTout = maxTransferTime(dummy.length, kMinTransferRate);
boolean transfferInTime = assert_Disconnected_wait(transferTout); boolean transfferInTime = assert_Disconnected_wait(transferTout);
elapsed = PseudoTCPBase.Now() - start; elapsed = PseudoTCPBase.now() - start;
StopClocks(); stopClocks();
int received = recv_stream.GetBuffered(); int received = recv_stream.getBuffered();
assertEquals("Transfer timeout, transferred: " + received assertEquals("Transfer timeout, transferred: " + received
+ " required: " + dummy.length + " required: " + dummy.length
+ " elapsed: " + " elapsed: "
@ -98,7 +98,7 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
assert 2 == send_position.size(); assert 2 == send_position.size();
assert 2 == recv_position.size(); assert 2 == recv_position.size();
int estimated_recv_window = EstimateReceiveWindowSize(); int estimated_recv_window = estimateReceiveWindowSize();
// The difference in consecutive send positions should equal the // The difference in consecutive send positions should equal the
// receive window size or match very closely. This verifies that receive // receive window size or match very closely. This verifies that receive
@ -145,17 +145,17 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
* *
* @throws IOException * @throws IOException
*/ */
void ReadUntilIOPending() throws IOException void readUntilIOPending() throws IOException
{ {
byte[] block = new byte[getRemoteTcp().getRecvBufferSize() * 2]; byte[] block = new byte[getRemoteTcp().getRecvBufferSize() * 2];
int position = recv_stream.GetBuffered(); int position = recv_stream.getBuffered();
int rcvd, total = 0; int rcvd, total = 0;
do do
{ {
rcvd = RemoteRecv(block, block.length); rcvd = remoteRecv(block, block.length);
if (rcvd > 0) if (rcvd > 0)
{ {
recv_stream.Write(block, rcvd); recv_stream.write(block, rcvd);
total += rcvd; total += rcvd;
position += rcvd; position += rcvd;
} }
@ -166,12 +166,12 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
// Disconnect if we have done two transfers. // Disconnect if we have done two transfers.
if (recv_position.size() == 2) if (recv_position.size() == 2)
{ {
Close(); close();
OnTcpClosed(getRemoteTcp(), null); onTcpClosed(getRemoteTcp(), null);
} }
else else
{ {
WriteData(); writeData();
} }
} }
@ -180,7 +180,7 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
* *
* @param delay * @param delay
*/ */
void ScheduleWriteAction(long delay) void scheduleWriteAction(long delay)
{ {
writeTimer.schedule(new TimerTask() writeTimer.schedule(new TimerTask()
{ {
@ -189,7 +189,7 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
{ {
try try
{ {
WriteData(); writeData();
} }
catch (IOException ex) catch (IOException ex)
{ {
@ -206,27 +206,27 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
* *
* @throws IOException * @throws IOException
*/ */
void WriteData() throws IOException void writeData() throws IOException
{ {
//writeOpCount++; //writeOpCount++;
int tosend; int tosend;
int sent; int sent;
int totalSent = 0; int totalSent = 0;
byte[] block = new byte[getRemoteTcp().getRecvBufferSize() * 2]; byte[] block = new byte[getRemoteTcp().getRecvBufferSize() * 2];
int position = testDataSize - send_stream.GetBuffered(); int position = testDataSize - send_stream.getBuffered();
synchronized (getLocalTcp()) synchronized (getLocalTcp())
{ {
do do
{ {
tosend = send_stream.ReadOffset(block, 0, block.length, 0); tosend = send_stream.readOffset(block, 0, block.length, 0);
if (tosend > 0) if (tosend > 0)
{ {
sent = LocalSend(block, tosend); sent = localSend(block, tosend);
UpdateLocalClock(); updateLocalClock();
if (sent > 0) if (sent > 0)
{ {
totalSent += sent; totalSent += sent;
send_stream.ConsumeReadData(sent); send_stream.consumeReadData(sent);
position += sent; position += sent;
} }
else else
@ -244,12 +244,12 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
} }
// Measured with precision according to window scale option used // Measured with precision according to window scale option used
if (totalSent - getRemoteTcp().GetAvailable() if (totalSent - getRemoteTcp().getAvailable()
> getShadowedBytes(getRemoteScaleFactor())) > getShadowedBytes(getRemoteScaleFactor()))
{ {
//send buffer was fully filled //send buffer was fully filled
//waits until it will be received by remote peer //waits until it will be received by remote peer
while (totalSent - getRemoteTcp().GetAvailable() while (totalSent - getRemoteTcp().getAvailable()
> getShadowedBytes(getRemoteScaleFactor()) > getShadowedBytes(getRemoteScaleFactor())
&& !getRemoteTcp().isReceiveBufferFull()) && !getRemoteTcp().isReceiveBufferFull())
{ {
@ -260,8 +260,8 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
{ {
logger.log(Level.FINER, logger.log(Level.FINER,
"Waiting... sent: " + totalSent + " avail: " "Waiting... sent: " + totalSent + " avail: "
+ getRemoteTcp().GetAvailable() + " buffered not sent: " + getRemoteTcp().getAvailable() + " buffered not sent: "
+ getLocalTcp().GetBytesBufferedNotSent() + getLocalTcp().getBytesBufferedNotSent()
+ " isFull? " + getRemoteTcp().isReceiveBufferFull()); + " isFull? " + getRemoteTcp().isReceiveBufferFull());
} }
} }
@ -279,7 +279,7 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
{ {
try try
{ {
ReadUntilIOPending(); readUntilIOPending();
} }
catch (IOException ex) catch (IOException ex)
{ {
@ -293,7 +293,7 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
* *
* @return estimated receive window size * @return estimated receive window size
*/ */
int EstimateReceiveWindowSize() int estimateReceiveWindowSize()
{ {
return recv_position.get(0); return recv_position.get(0);
} }
@ -302,24 +302,24 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
* *
* @return estimated send window size * @return estimated send window size
*/ */
int EstimateSendWindowSize() int estimateSendWindowSize()
{ {
return send_position.get(0); return send_position.get(0);
} }
@Override @Override
public void OnTcpReadable(PseudoTCPBase tcp) public void onTcpReadable(PseudoTCPBase tcp)
{ {
} }
@Override @Override
public void OnTcpWriteable(PseudoTCPBase tcp) public void onTcpWriteable(PseudoTCPBase tcp)
{ {
} }
void SetLocalOptSndBuf(int len) void setLocalOptSndBuf(int len)
{ {
getLocalTcp().SetOption(Option.OPT_SNDBUF, len); getLocalTcp().setOption(Option.OPT_SNDBUF, len);
} }
int getRemoteScaleFactor() int getRemoteScaleFactor()
@ -345,11 +345,11 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test receive window"); //logger.log(Level.INFO, "Test receive window");
PseudoTcpTestRecvWindow test = new PseudoTcpTestRecvWindow(); PseudoTcpTestRecvWindow test = new PseudoTcpTestRecvWindow();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetOptNagling(false); test.setOptNagling(false);
test.SetOptAckDelay(0); test.setOptAckDelay(0);
test.TestTransfer(1024 * 1000); test.doTestTransfer(1024 * 1000);
} }
/** /**
@ -360,13 +360,13 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
//TODO: finish test //TODO: finish test
logger.log(Level.INFO, "Test very small receive window"); logger.log(Level.INFO, "Test very small receive window");
PseudoTcpTestRecvWindow test = new PseudoTcpTestRecvWindow(); PseudoTcpTestRecvWindow test = new PseudoTcpTestRecvWindow();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetOptNagling(false); test.setOptNagling(false);
test.SetOptAckDelay(0); test.setOptAckDelay(0);
test.SetOptSndBuf(900); test.setOptSndBuf(900);
test.TestTransfer(1024 * 1000); test.doTestTransfer(1024 * 1000);
assertEquals(900, test.EstimateSendWindowSize()); assertEquals(900, test.estimateSendWindowSize());
} }
/** /**
@ -376,21 +376,21 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test set receive window size"); //logger.log(Level.INFO, "Test set receive window size");
PseudoTcpTestRecvWindow test = new PseudoTcpTestRecvWindow(); PseudoTcpTestRecvWindow test = new PseudoTcpTestRecvWindow();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetOptNagling(false); test.setOptNagling(false);
test.SetOptAckDelay(0); test.setOptAckDelay(0);
int wndSize = 300000; int wndSize = 300000;
test.SetRemoteOptRcvBuf(wndSize); test.setRemoteOptRcvBuf(wndSize);
test.SetLocalOptSndBuf(wndSize); test.setLocalOptSndBuf(wndSize);
int wndScale = test.getRemoteScaleFactor(); int wndScale = test.getRemoteScaleFactor();
//logger.log(Level.INFO, "Using scale factor: {0}", wndScale); //logger.log(Level.INFO, "Using scale factor: {0}", wndScale);
test.TestTransfer(1024 * 3000); test.doTestTransfer(1024 * 3000);
//beacuse there may be situations //beacuse there may be situations
//when 1 byte may be waiting in send queue //when 1 byte may be waiting in send queue
//before //before
//scaling factor == 1 not allows to determine exact window size (+-1) //scaling factor == 1 not allows to determine exact window size (+-1)
assert (wndSize - test.EstimateReceiveWindowSize() assert (wndSize - test.estimateReceiveWindowSize()
<= PseudoTcpTestRecvWindow.getShadowedBytes(wndScale)); <= PseudoTcpTestRecvWindow.getShadowedBytes(wndScale));
} }

View File

@ -52,7 +52,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
* *
* @param size * @param size
*/ */
public void TestTransfer(int size) public void doTestTransfer(int size)
{ {
Thread.setDefaultUncaughtExceptionHandler(this); Thread.setDefaultUncaughtExceptionHandler(this);
long start, elapsed; long start, elapsed;
@ -64,11 +64,11 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
// Prepare the receive stream. // Prepare the receive stream.
recvStream = new ByteArrayOutputStream(size); recvStream = new ByteArrayOutputStream(size);
// Connect and wait until connected. // Connect and wait until connected.
start = PseudoTCPBase.Now(); start = PseudoTCPBase.now();
StartClocks(); startClocks();
try try
{ {
Connect(); connect();
//assertEquals(0, Connect()); //assertEquals(0, Connect());
} }
catch (IOException ex) catch (IOException ex)
@ -79,10 +79,10 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
assert_Connected_wait(kConnectTimeoutMs); assert_Connected_wait(kConnectTimeoutMs);
// Sending will start from OnTcpWriteable and complete when all data has // Sending will start from OnTcpWriteable and complete when all data has
// been received. // been received.
long transferTout = MaxTransferTime(sendData.length, kMinTransferRate); long transferTout = maxTransferTime(sendData.length, kMinTransferRate);
boolean transfferInTime = assert_Disconnected_wait(transferTout); boolean transfferInTime = assert_Disconnected_wait(transferTout);
elapsed = PseudoTCPBase.Now() - start; elapsed = PseudoTCPBase.now() - start;
StopClocks(); stopClocks();
received = recvStream.size(); received = recvStream.size();
assertEquals("Transfer timeout, transferred: " + received assertEquals("Transfer timeout, transferred: " + received
+ " required: " + sendData.length + " required: " + sendData.length
@ -106,14 +106,14 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
* *
* @throws IOException * @throws IOException
*/ */
void ReadData() throws IOException void readData() throws IOException
{ {
byte[] block = new byte[kBlockSize]; byte[] block = new byte[kBlockSize];
int rcvd; int rcvd;
do do
{ {
rcvd = RemoteRecv(block, block.length); rcvd = remoteRecv(block, block.length);
UpdateRemoteClock(); updateRemoteClock();
if (rcvd != -1) if (rcvd != -1)
{ {
recvStream.write(block, 0, rcvd); recvStream.write(block, 0, rcvd);
@ -128,7 +128,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
* @return true if there's no more data left to write * @return true if there's no more data left to write
* @throws IOException * @throws IOException
*/ */
boolean WriteData() throws IOException boolean writeData() throws IOException
{ {
int tosend; int tosend;
int sent; int sent;
@ -139,8 +139,8 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
System.arraycopy(sendData, totalSent, block, 0, tosend); System.arraycopy(sendData, totalSent, block, 0, tosend);
if (tosend > 0) if (tosend > 0)
{ {
sent = LocalSend(block, tosend); sent = localSend(block, tosend);
UpdateLocalClock(); updateLocalClock();
if (sent != -1) if (sent != -1)
{ {
totalSent += sent; totalSent += sent;
@ -173,13 +173,13 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
* @param tcp * @param tcp
*/ */
@Override @Override
public void OnTcpReadable(PseudoTCPBase tcp) public void onTcpReadable(PseudoTCPBase tcp)
{ {
if (tcp == getRemoteTcp()) if (tcp == getRemoteTcp())
{ {
try try
{ {
ReadData(); readData();
// TODO: OnTcpClosed() is currently only notified on error - // TODO: OnTcpClosed() is currently only notified on error -
// there is no on-the-wire equivalent of TCP FIN. // there is no on-the-wire equivalent of TCP FIN.
// So we fake the notification when all the data has been read. // So we fake the notification when all the data has been read.
@ -193,7 +193,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
} }
if (received == required) if (received == required)
{ {
OnTcpClosed(getRemoteTcp(), null); onTcpClosed(getRemoteTcp(), null);
} }
} }
catch (IOException ex) catch (IOException ex)
@ -210,7 +210,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
* @param tcp * @param tcp
*/ */
@Override @Override
public void OnTcpWriteable(PseudoTCPBase tcp) public void onTcpWriteable(PseudoTCPBase tcp)
{ {
if (tcp == getLocalTcp()) if (tcp == getLocalTcp())
{ {
@ -219,9 +219,9 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
logger.log(Level.FINER, "Flow Control Lifted"); logger.log(Level.FINER, "Flow Control Lifted");
try try
{ {
if (WriteData()) if (writeData())
{ {
Close(); close();
} }
} }
catch (IOException ex) catch (IOException ex)
@ -240,9 +240,9 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test send"); //logger.log(Level.INFO, "Test send");
PseudoTcpTestTransfer test = new PseudoTcpTestTransfer(); PseudoTcpTestTransfer test = new PseudoTcpTestTransfer();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.TestTransfer(1000000); test.doTestTransfer(1000000);
} }
/** /**
@ -253,10 +253,10 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test send with delay"); //logger.log(Level.INFO, "Test send with delay");
PseudoTcpTestTransfer test = new PseudoTcpTestTransfer(); PseudoTcpTestTransfer test = new PseudoTcpTestTransfer();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetDelay(50); test.setDelay(50);
test.TestTransfer(1000000); test.doTestTransfer(1000000);
} }
/** /**
@ -267,10 +267,10 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test send with loss"); //logger.log(Level.INFO, "Test send with loss");
PseudoTcpTestTransfer test = new PseudoTcpTestTransfer(); PseudoTcpTestTransfer test = new PseudoTcpTestTransfer();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetLoss(10); test.setLoss(10);
test.TestTransfer(100000); // less data so test runs faster test.doTestTransfer(100000); // less data so test runs faster
} }
/** /**
@ -282,11 +282,11 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test send with delay and loss"); //logger.log(Level.INFO, "Test send with delay and loss");
PseudoTcpTestTransfer test = new PseudoTcpTestTransfer(); PseudoTcpTestTransfer test = new PseudoTcpTestTransfer();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetDelay(50); test.setDelay(50);
test.SetLoss(10); test.setLoss(10);
test.TestTransfer(100000); // less data so test runs faster test.doTestTransfer(100000); // less data so test runs faster
} }
/** /**
@ -297,11 +297,11 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test send with loss and OptNagling off"); //logger.log(Level.INFO, "Test send with loss and OptNagling off");
PseudoTcpTestTransfer test = new PseudoTcpTestTransfer(); PseudoTcpTestTransfer test = new PseudoTcpTestTransfer();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetLoss(10); test.setLoss(10);
test.SetOptNagling(false); test.setOptNagling(false);
test.TestTransfer(100000); // less data so test runs faster test.doTestTransfer(100000); // less data so test runs faster
} }
/** /**
@ -312,11 +312,11 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test send with loss and OptAckDelay off"); //logger.log(Level.INFO, "Test send with loss and OptAckDelay off");
PseudoTcpTestTransfer test = new PseudoTcpTestTransfer(); PseudoTcpTestTransfer test = new PseudoTcpTestTransfer();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetLoss(10); test.setLoss(10);
test.SetOptAckDelay(0); test.setOptAckDelay(0);
test.TestTransfer(100000); test.doTestTransfer(100000);
} }
/** /**
@ -326,11 +326,11 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test send with delay and OptNagling off"); //logger.log(Level.INFO, "Test send with delay and OptNagling off");
PseudoTcpTestTransfer test = new PseudoTcpTestTransfer(); PseudoTcpTestTransfer test = new PseudoTcpTestTransfer();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetDelay(50); test.setDelay(50);
test.SetOptNagling(false); test.setOptNagling(false);
test.TestTransfer(100000); // less data so test runs faster test.doTestTransfer(100000); // less data so test runs faster
} }
/** /**
@ -340,11 +340,11 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test send with delay and OptAckDelay off"); //logger.log(Level.INFO, "Test send with delay and OptAckDelay off");
PseudoTcpTestTransfer test = new PseudoTcpTestTransfer(); PseudoTcpTestTransfer test = new PseudoTcpTestTransfer();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetDelay(50); test.setDelay(50);
test.SetOptAckDelay(0); test.setOptAckDelay(0);
test.TestTransfer(100000); // less data so test runs faster test.doTestTransfer(100000); // less data so test runs faster
} }
/** /**
@ -354,11 +354,11 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test send - remote no window scale"); //logger.log(Level.INFO, "Test send - remote no window scale");
PseudoTcpTestTransfer test = new PseudoTcpTestTransfer(); PseudoTcpTestTransfer test = new PseudoTcpTestTransfer();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetLocalOptRcvBuf(100000); test.setLocalOptRcvBuf(100000);
test.DisableRemoteWindowScale(); test.disableRemoteWindowScale();
test.TestTransfer(1000000); test.doTestTransfer(1000000);
} }
/** /**
@ -369,11 +369,11 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test send - local no window scale"); //logger.log(Level.INFO, "Test send - local no window scale");
PseudoTcpTestTransfer test = new PseudoTcpTestTransfer(); PseudoTcpTestTransfer test = new PseudoTcpTestTransfer();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetRemoteOptRcvBuf(100000); test.setRemoteOptRcvBuf(100000);
test.DisableLocalWindowScale(); test.disableLocalWindowScale();
test.TestTransfer(1000000); test.doTestTransfer(1000000);
} }
/** /**
@ -383,11 +383,11 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test send - both use window scale"); //logger.log(Level.INFO, "Test send - both use window scale");
PseudoTcpTestTransfer test = new PseudoTcpTestTransfer(); PseudoTcpTestTransfer test = new PseudoTcpTestTransfer();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetRemoteOptRcvBuf(100000); test.setRemoteOptRcvBuf(100000);
test.SetLocalOptRcvBuf(100000); test.setLocalOptRcvBuf(100000);
test.TestTransfer(1000000); test.doTestTransfer(1000000);
} }
/** /**
@ -397,23 +397,23 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test send large in flight"); //logger.log(Level.INFO, "Test send large in flight");
PseudoTcpTestTransfer test = new PseudoTcpTestTransfer(); PseudoTcpTestTransfer test = new PseudoTcpTestTransfer();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetRemoteOptRcvBuf(100000); test.setRemoteOptRcvBuf(100000);
test.SetLocalOptRcvBuf(100000); test.setLocalOptRcvBuf(100000);
test.SetOptSndBuf(150000); test.setOptSndBuf(150000);
test.TestTransfer(1000000); test.doTestTransfer(1000000);
} }
public void testSendBothUseLargeWindowScale() public void testSendBothUseLargeWindowScale()
{ {
//logger.log(Level.INFO, "Test send both use large window scale"); //logger.log(Level.INFO, "Test send both use large window scale");
PseudoTcpTestTransfer test = new PseudoTcpTestTransfer(); PseudoTcpTestTransfer test = new PseudoTcpTestTransfer();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetRemoteOptRcvBuf(1000000); test.setRemoteOptRcvBuf(1000000);
test.SetLocalOptRcvBuf(1000000); test.setLocalOptRcvBuf(1000000);
test.TestTransfer(10000000); test.doTestTransfer(10000000);
} }
/** /**
@ -423,11 +423,11 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test send small receive buffer"); //logger.log(Level.INFO, "Test send small receive buffer");
PseudoTcpTestTransfer test = new PseudoTcpTestTransfer(); PseudoTcpTestTransfer test = new PseudoTcpTestTransfer();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetRemoteOptRcvBuf(10000); test.setRemoteOptRcvBuf(10000);
test.SetLocalOptRcvBuf(10000); test.setLocalOptRcvBuf(10000);
test.TestTransfer(1000000); test.doTestTransfer(1000000);
} }
/** /**
@ -437,10 +437,10 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
{ {
//logger.log(Level.INFO, "Test send very small receive buffer"); //logger.log(Level.INFO, "Test send very small receive buffer");
PseudoTcpTestTransfer test = new PseudoTcpTestTransfer(); PseudoTcpTestTransfer test = new PseudoTcpTestTransfer();
test.SetLocalMtu(1500); test.setLocalMtu(1500);
test.SetRemoteMtu(1500); test.setRemoteMtu(1500);
test.SetRemoteOptRcvBuf(100); test.setRemoteOptRcvBuf(100);
test.SetLocalOptRcvBuf(100); test.setLocalOptRcvBuf(100);
test.TestTransfer(100000); test.doTestTransfer(100000);
} }
} }

View File

@ -31,10 +31,10 @@ public class ByteFifoBufferTest
{ {
int expResult = 1000; int expResult = 1000;
ByteFifoBuffer instance = new ByteFifoBuffer(expResult); ByteFifoBuffer instance = new ByteFifoBuffer(expResult);
assertEquals(expResult, instance.Length()); assertEquals(expResult, instance.length());
int wSize = 100; int wSize = 100;
instance.Write(getWData(wSize), wSize); instance.write(getWData(wSize), wSize);
int result = instance.Length(); int result = instance.length();
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@ -46,11 +46,11 @@ public class ByteFifoBufferTest
int count = 1024; int count = 1024;
byte[] wData = getWData(count); byte[] wData = getWData(count);
ByteFifoBuffer instance = new ByteFifoBuffer(count); ByteFifoBuffer instance = new ByteFifoBuffer(count);
instance.Write(wData, count); instance.write(wData, count);
byte[] readBuff = new byte[count]; byte[] readBuff = new byte[count];
int expResult = count; int expResult = count;
int result = instance.Read(readBuff, count); int result = instance.read(readBuff, count);
assertEquals(expResult, result); assertEquals(expResult, result);
assertArrayEquals(wData, readBuff); assertArrayEquals(wData, readBuff);
@ -64,14 +64,14 @@ public class ByteFifoBufferTest
int count = 1024; int count = 1024;
byte[] wData = getWData(count); byte[] wData = getWData(count);
ByteFifoBuffer instance = new ByteFifoBuffer(count); ByteFifoBuffer instance = new ByteFifoBuffer(count);
instance.Write(wData, count); instance.write(wData, count);
byte[] readBuff = new byte[count]; byte[] readBuff = new byte[count];
int expResult = count / 2; int expResult = count / 2;
int result = instance.Read(readBuff, count / 2); int result = instance.read(readBuff, count / 2);
assertEquals(expResult, result); assertEquals(expResult, result);
result = instance.Read(readBuff, count / 2, count / 2); result = instance.read(readBuff, count / 2, count / 2);
assertEquals(expResult, result); assertEquals(expResult, result);
assertArrayEquals(wData, readBuff); assertArrayEquals(wData, readBuff);
@ -100,15 +100,15 @@ public class ByteFifoBufferTest
int len = 100; int len = 100;
ByteFifoBuffer instance = new ByteFifoBuffer(len); ByteFifoBuffer instance = new ByteFifoBuffer(len);
int expResult = len; int expResult = len;
int result = instance.GetWriteRemaining(); int result = instance.getWriteRemaining();
assertEquals(expResult, result); assertEquals(expResult, result);
int w_size = 23; int w_size = 23;
byte[] w_data = getWData(w_size); byte[] w_data = getWData(w_size);
instance.Write(w_data, w_size); instance.write(w_data, w_size);
expResult = len - w_size; expResult = len - w_size;
result = instance.GetWriteRemaining(); result = instance.getWriteRemaining();
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@ -122,15 +122,15 @@ public class ByteFifoBufferTest
int w_len = 100; int w_len = 100;
byte[] w_data = getWData(w_len); byte[] w_data = getWData(w_len);
instance.Write(w_data, w_len); instance.write(w_data, w_len);
int expResult = w_len; int expResult = w_len;
int result = instance.GetBuffered(); int result = instance.getBuffered();
assertEquals(expResult, result); assertEquals(expResult, result);
int consume = 5; int consume = 5;
expResult = w_len + consume; expResult = w_len + consume;
instance.ConsumeWriteBuffer(consume); instance.consumeWriteBuffer(consume);
result = instance.GetBuffered(); result = instance.getBuffered();
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@ -143,11 +143,11 @@ public class ByteFifoBufferTest
byte[] data = getWData(len); byte[] data = getWData(len);
ByteFifoBuffer instance = new ByteFifoBuffer(len); ByteFifoBuffer instance = new ByteFifoBuffer(len);
int expResult = len; int expResult = len;
int result = instance.Write(data, len); int result = instance.write(data, len);
assertEquals(expResult, result); assertEquals(expResult, result);
byte[] read = new byte[len]; byte[] read = new byte[len];
int readCount = instance.Read(read, len); int readCount = instance.read(read, len);
assertEquals(result, readCount); assertEquals(result, readCount);
assertArrayEquals(data, read); assertArrayEquals(data, read);
} }
@ -158,13 +158,13 @@ public class ByteFifoBufferTest
byte[] data = getWData(len); byte[] data = getWData(len);
ByteFifoBuffer instance = new ByteFifoBuffer(len); ByteFifoBuffer instance = new ByteFifoBuffer(len);
int expResult = len / 2; int expResult = len / 2;
int result = instance.Write(data, 0, len / 2); int result = instance.write(data, 0, len / 2);
assertEquals(expResult, result); assertEquals(expResult, result);
result = instance.Write(data, len / 2, len / 2); result = instance.write(data, len / 2, len / 2);
assertEquals(expResult, result); assertEquals(expResult, result);
byte[] read = new byte[len]; byte[] read = new byte[len];
int readCount = instance.Read(read, len); int readCount = instance.read(read, len);
assertEquals(len, readCount); assertEquals(len, readCount);
assertArrayEquals(data, read); assertArrayEquals(data, read);
} }
@ -176,11 +176,11 @@ public class ByteFifoBufferTest
{ {
int len = 100; int len = 100;
ByteFifoBuffer instance = new ByteFifoBuffer(len); ByteFifoBuffer instance = new ByteFifoBuffer(len);
instance.ConsumeWriteBuffer(len / 2); instance.consumeWriteBuffer(len / 2);
instance.ConsumeWriteBuffer(len / 2); instance.consumeWriteBuffer(len / 2);
try try
{ {
instance.ConsumeWriteBuffer(1); instance.consumeWriteBuffer(1);
fail(); fail();
} }
catch (BufferOverflowException e) catch (BufferOverflowException e)
@ -188,9 +188,9 @@ public class ByteFifoBufferTest
} }
instance = new ByteFifoBuffer(len); instance = new ByteFifoBuffer(len);
instance.ConsumeWriteBuffer(95); instance.consumeWriteBuffer(95);
instance.ConsumeReadData(40); instance.consumeReadData(40);
instance.ConsumeWriteBuffer(20); instance.consumeWriteBuffer(20);
} }
@ -203,14 +203,14 @@ public class ByteFifoBufferTest
int new_size = 200; int new_size = 200;
ByteFifoBuffer instance = new ByteFifoBuffer(old_size); ByteFifoBuffer instance = new ByteFifoBuffer(old_size);
boolean expResult = true; boolean expResult = true;
instance.Write(getWData(old_size), old_size); instance.write(getWData(old_size), old_size);
boolean result = instance.SetCapacity(new_size); boolean result = instance.setCapacity(new_size);
assertEquals(expResult, result); assertEquals(expResult, result);
expResult = false; expResult = false;
instance.ResetWritePosition(); instance.resetWritePosition();
instance.Write(getWData(new_size), new_size); instance.write(getWData(new_size), new_size);
result = instance.SetCapacity(old_size); result = instance.setCapacity(old_size);
assertEquals(expResult, result); assertEquals(expResult, result);
} }
@ -222,12 +222,12 @@ public class ByteFifoBufferTest
{ {
int lCount = 100; int lCount = 100;
ByteFifoBuffer instance = new ByteFifoBuffer(lCount); ByteFifoBuffer instance = new ByteFifoBuffer(lCount);
instance.Write(getWData(lCount), lCount); instance.write(getWData(lCount), lCount);
instance.ConsumeReadData(lCount / 2); instance.consumeReadData(lCount / 2);
instance.ConsumeReadData(lCount / 2); instance.consumeReadData(lCount / 2);
try try
{ {
instance.ConsumeReadData(1); instance.consumeReadData(1);
fail(); fail();
} }
catch (BufferUnderflowException e) catch (BufferUnderflowException e)
@ -248,9 +248,9 @@ public class ByteFifoBufferTest
int offset = 0; int offset = 0;
ByteFifoBuffer instance = new ByteFifoBuffer(len); ByteFifoBuffer instance = new ByteFifoBuffer(len);
int expResult = len; int expResult = len;
instance.Write(src_buff, len); instance.write(src_buff, len);
int result = int result =
instance.ReadOffset(dst_buff, dst_buff_offset, len, offset); instance.readOffset(dst_buff, dst_buff_offset, len, offset);
assertEquals(expResult, result); assertEquals(expResult, result);
assertArrayEquals(dst_buff, src_buff); assertArrayEquals(dst_buff, src_buff);
@ -267,26 +267,26 @@ public class ByteFifoBufferTest
byte[] data = new byte[dataLen]; byte[] data = new byte[dataLen];
int nOffset = 10; int nOffset = 10;
ByteFifoBuffer instance = new ByteFifoBuffer(len); ByteFifoBuffer instance = new ByteFifoBuffer(len);
int result = instance.WriteOffset(srcData, dataLen, nOffset); int result = instance.writeOffset(srcData, dataLen, nOffset);
int readCount = instance.ReadOffset(data, 0, dataLen, nOffset); int readCount = instance.readOffset(data, 0, dataLen, nOffset);
assertEquals(result, readCount); assertEquals(result, readCount);
assertArrayEquals(srcData, data); assertArrayEquals(srcData, data);
byte[] halfFilled = new byte[dataLen * 2]; byte[] halfFilled = new byte[dataLen * 2];
System.arraycopy(srcData, 0, halfFilled, dataLen, dataLen); System.arraycopy(srcData, 0, halfFilled, dataLen, dataLen);
byte[] halfFilledRead = new byte[dataLen * 2]; byte[] halfFilledRead = new byte[dataLen * 2];
instance.ReadOffset(halfFilledRead, dataLen, dataLen, nOffset); instance.readOffset(halfFilledRead, dataLen, dataLen, nOffset);
assertArrayEquals(halfFilled, halfFilledRead); assertArrayEquals(halfFilled, halfFilledRead);
// case when w_pos+offset exceeds current backing array length // case when w_pos+offset exceeds current backing array length
instance = new ByteFifoBuffer(len); instance = new ByteFifoBuffer(len);
instance.Write(srcData, dataLen); instance.write(srcData, dataLen);
instance.Write(srcData, dataLen / 2);// current writePos = 150 instance.write(srcData, dataLen / 2);// current writePos = 150
instance.Read(data, dataLen);// curretn readPos = 100 instance.read(data, dataLen);// curretn readPos = 100
instance.WriteOffset(srcData, dataLen, 50); instance.writeOffset(srcData, dataLen, 50);
instance = new ByteFifoBuffer(61440); instance = new ByteFifoBuffer(61440);
instance.WriteOffset(getWData(1384), 1384, 31832); instance.writeOffset(getWData(1384), 1384, 31832);
} }
@ -300,19 +300,19 @@ public class ByteFifoBufferTest
int read = 0; int read = 0;
do do
{ {
int wrRemaining = instance.GetWriteRemaining(); int wrRemaining = instance.getWriteRemaining();
if (wrRemaining > 0 && written < wrData.length) if (wrRemaining > 0 && written < wrData.length)
{ {
int wrCount = instance.WriteOffset(wrData, wrRemaining, 0); int wrCount = instance.writeOffset(wrData, wrRemaining, 0);
instance.ConsumeWriteBuffer(wrCount); instance.consumeWriteBuffer(wrCount);
written += wrCount; written += wrCount;
} }
int readAvailable = instance.GetBuffered(); int readAvailable = instance.getBuffered();
if (readAvailable > 0) if (readAvailable > 0)
{ {
int rCount = int rCount =
instance.ReadOffset(readBuff, read, readAvailable, 0); instance.readOffset(readBuff, read, readAvailable, 0);
instance.ConsumeReadData(rCount); instance.consumeReadData(rCount);
read += rCount; read += rCount;
} }
} }
@ -336,9 +336,9 @@ public class ByteFifoBufferTest
byte[] Cread = getWData(Clen); byte[] Cread = getWData(Clen);
byte[] Dread = getWData(Dlen); byte[] Dread = getWData(Dlen);
fifo.WriteOffset(A, Alen, 0); fifo.writeOffset(A, Alen, 0);
fifo.ConsumeWriteBuffer(Alen); fifo.consumeWriteBuffer(Alen);
fifo.ReadOffset(Aread, 0, Alen, 0); fifo.readOffset(Aread, 0, Alen, 0);
assertArrayEquals(A, Aread); assertArrayEquals(A, Aread);
} }
} }

View File

@ -284,7 +284,7 @@ public class IcePseudoTcp
public static void main(String[] args) throws Throwable public static void main(String[] args) throws Throwable
{ {
startTime = System.currentTimeMillis(); startTime = System.currentTimeMillis();
int localPort = 7999; int localPort = 7999;
int remotePort = 6000; int remotePort = 6000;
@ -376,12 +376,14 @@ public class IcePseudoTcp
{ {
logger.log(Level.INFO, logger.log(Level.INFO,
"Local pseudotcp is using: " "Local pseudotcp is using: "
+ dgramSocket.getLocalSocketAddress()); + dgramSocket.getLocalSocketAddress()+dgramSocket);
PseudoTcpSocketImpl socket = new PseudoTcpSocketImpl(
1073741824, dgramSocket); PseudoTcpSocket socket = new PseudoTcpSocketFactory().
createSocket(dgramSocket);
socket.setConversationID(1073741824);
socket.setMTU(1500); socket.setMTU(1500);
socket.setDebugName("L"); socket.setDebugName("L");
socket.Accept(5000); socket.accept(5000);
byte[] buffer = new byte[TEST_BYTES_COUNT]; byte[] buffer = new byte[TEST_BYTES_COUNT];
int read = 0; int read = 0;
while (read != TEST_BYTES_COUNT) while (read != TEST_BYTES_COUNT)
@ -423,13 +425,14 @@ public class IcePseudoTcp
"Remote pseudotcp is using: " + "Remote pseudotcp is using: " +
dgramSocket.getLocalSocketAddress() dgramSocket.getLocalSocketAddress()
+" and will comunicate with: " + peerAddr); +" and will comunicate with: " + peerAddr);
PseudoTcpSocketImpl socket = new PseudoTcpSocketImpl( PseudoTcpSocket socket = new PseudoTcpSocketFactory().
1073741824, dgramSocket); createSocket(dgramSocket);
socket.setConversationID(1073741824);
socket.setMTU(1500); socket.setMTU(1500);
socket.setDebugName("R"); socket.setDebugName("R");
long start, end; long start, end;
start = System.currentTimeMillis(); start = System.currentTimeMillis();
socket.Connect(peerAddr, 5000); socket.connect(peerAddr, 5000);
byte[] buffer = new byte[TEST_BYTES_COUNT]; byte[] buffer = new byte[TEST_BYTES_COUNT];
socket.getOutputStream().write(buffer); socket.getOutputStream().write(buffer);
socket.getOutputStream().flush(); socket.getOutputStream().flush();