jist.swans.trans
Class TcpSocket

java.lang.Object
  extended by jist.swans.trans.TcpSocket
All Implemented Interfaces:
JistAPI.Proxiable, JistAPI.Timeless, SocketInterface, SocketInterface.TcpSocketInterface

public class TcpSocket
extends java.lang.Object
implements SocketInterface.TcpSocketInterface

SWANS Implementation of Socket entity.

Since:
SWANS1.0
Version:
$Id: TcpSocket.java,v 1.20 2004/04/06 16:07:51 barr Exp $
Author:
Kelwin Tamtoro <kt222@cs.cornell.edu>, Rimon Barr <barr+jist@cs.cornell.edu>

Nested Class Summary
static class TcpSocket.TcpSocketCallback
          Implementation of Socket Callback for TcpSocket.
 
Nested classes/interfaces inherited from interface jist.swans.trans.SocketInterface
SocketInterface.TcpServerSocketInterface, SocketInterface.TcpSocketInterface
 
Field Summary
private  TransInterface.SocketHandler.TcpHandler callback
          A callback object used by other entities to call this socket.
private  Channel channel
          A channel for blocking send/receive.
private  boolean connectInConstructor
          booleans to support TCP implementation.
private  int currentState
          State of the TCP connection.
private  short cwnd
          congestion window.
private  double cwnd_increment
          to hold the increment of congestion window during congestion avoidance.
static long DELAYED_ACK_TIME
          Number of milliseconds to wait before sending an ACK.
private  int dupAckCounter
          counter for number of duplicate ACKs that we currently receive.
static int FULL_DEBUG
          Debug printing flag.
private  TcpInputStream in
          Input Stream for this connection.
static int INFO
          Debug printing flag.
static short INIT_WINDOW_SIZE
          Initial window size.
private  int initAckNum
          Initial acknowledgement number.
private  int initSeqNum
          Initial sequence number.
private  boolean isApplicationWaiting
          flag to note if application layer is waiting for messages.
private  boolean isBound
          booleans to support socket implementation.
private  boolean isClosed
          booleans to support socket implementation.
private  boolean isClosing
          booleans to support TCP implementation.
private  boolean isConnected
          booleans to support socket implementation.
private  boolean isTcpNoDelay
          booleans to support socket implementation.
private  NetAddress laddr
          Local address for the connection.
private  short last_adv_wnd
          the receiving window that we most recently advertised.
private  int lport
          Local port number for the connection.
static int MSL
          Maximum Segment Lifetime.
static int MSS
          Maximum Segment Size.
private  int numBytesRequest
          number of bytes requested by application layer while waiting.
static int OFF
          Debug printing flag.
private  TcpOutputStream out
          Output Stream for this connection.
private  int packetCounter
          Number of packets sent by the socket.
static long PERSIST_TIMER
          Number of seconds to wait before sending probe packets.
private  int persistTimerId
          ID for persist timer.
static int PRINTOUT
          Indicator for printing debug outputs.
private  int probeCounter
          to count how many probes we have received for this current session (session means the time when the receiver advertises zero window).
private  TransTcp.TcpMessage probeMessage
          temporary variable to store the current probe message (if not null).
private  NetAddress raddr
          Remote address for the connection.
private  int rcv_nxt
          next sequence number expected on an incoming segment.
private  short rcv_wnd
          receiver window.
private  CircularBuffer receiveBuffer
          Buffers to hold bytes received.
private  int resetTimerId
          ID for reset timer (for special cases).
static long RETRANSMIT_TIMEOUT
          Number of seconds to wait for first retransmission timer.
static long RETRANSMIT_TIMEOUT_FINAL
          Number of seconds to wait for second retransmission timer.
private  PriorityList rList
          a list to hold packets that might need to be retransmitted.
private  PriorityList rMsgBuffer
          a list to hold out-of-order received packets that are in window.
private  int rport
          Remote port number for the connection.
private  short rwnd
          most recently advertised receiver window.
private  SocketInterface.TcpSocketInterface self
          A pointer to this socket's proxy.
private  CircularBuffer sendBuffer
          Buffers to hold bytes to be sent.
private  int snd_nxt
          next sequence number to be sent.
private  int snd_una
          oldest unacknowledged sequence number.
private  short sshtresh
          threshold for slow start/congestion avoidance.
static int TCP_DEBUG
          Debug printing flag.
private  TransInterface.TransTcpInterface tcpEntity
          A reference to TCP Entity.
private  short temp_rcv_wnd
          temporary receiver window (used to hold update after some data are sent to application layer).
 
Constructor Summary
  TcpSocket()
          Creates an unconnected socket, with the system-default type of SocketImpl.
  TcpSocket(java.net.InetAddress address, int port)
          Creates a stream socket and connects it to the specified port number at the specified IP address.
  TcpSocket(java.net.InetAddress host, int port, boolean stream)
          Deprecated.
  TcpSocket(java.net.InetAddress address, int port, java.net.InetAddress localAddr, int localPort)
          Creates a socket and connects it to the specified remote address on the specified remote port.
protected TcpSocket(java.net.SocketImpl impl)
          Creates an unconnected Socket with a user-specified SocketImpl.
  TcpSocket(java.lang.String host, int port)
          Creates a stream socket and connects it to the specified port number on the named host.
  TcpSocket(java.lang.String host, int port, boolean stream)
          Deprecated.
  TcpSocket(java.lang.String host, int port, java.net.InetAddress localAddr, int localPort)
          Creates a socket and connects it to the specified remote host on the specified remote port.
protected TcpSocket(TransInterface.TransTcpInterface tcpEntity, java.net.InetAddress rAddr, short rPort, java.net.InetAddress lAddr, short lPort, int initialAckNum, short winSize)
          Creates an unconnected Socket with a user-specified TransInterface Entity and SYN packet received by TcpServerSocket.
 
Method Summary
 void _jistPostInit()
          Post-constructor call.
 void bind(java.net.SocketAddress bindpoint)
          Binds the ServerSocket to a specific address (IP address and port number).
private  void cancelPersistTimer()
          Cancel the current persist timer.
private  void cancelResetTimer()
          Cancel the current reset timer.
 void checkPacketandState(TransTcp.TcpMessage msg, NetAddress src)
          Check and process the incoming packet depending on current state of the socket.
 void close()
          Closes this socket.
private  void closeSocket(boolean doUnbind)
          This method is called when socket is to be closed.
private  long compareUnsignedInt(int a, int b)
          Returns the difference between two unsigned integers.
private  int compareUnsignedShort(short a, short b)
          Returns the difference between two unsigned shorts.
private  void CongestionAvoidance()
          This method implements Congestion Avoidance phase for congestion control.
private  void connect(java.net.InetAddress raddr, int rport, int timeout)
          Connects this socket to a specified address and timeout value.
 void connect(java.net.SocketAddress endpoint)
          Connects this socket to the server.
 void connect(java.net.SocketAddress endpoint, int timeout)
          Connects this socket to the server with a specified timeout value.
 void constructPackets()
          Creates packets to be sent based on the receiver's advertised window (managing flow control).
private  boolean createProbeMessage()
          Create a probe message (for persist timer) by extracting one byte of data from the send buffer.
 void createProxy()
          Create an entity reference to itself.
private  void createStreams()
          Create the input and output streams for this socket.
protected  void establishingConnection()
          this method is used to wait for incoming ACK packet for connection establishment.
private  void FastRetransmit()
          This method implements Fast Retransmit algorithm.
 byte[] getBytesFromSocket(int length)
          This method is called by the input stream to retrieve data from the transport layer.
 java.nio.channels.SocketChannel getChannel()
          Returns the unique SocketChannel object associated with this socket, if any.
private  short getCurrentReceiverWindow()
          Returns the smaller window (between the last advertised window and the congestion window) for the receiver.
private  java.lang.String getCurrentStateString()
          Returns the string name of current state.
 java.net.InetAddress getInetAddress()
          Returns the local address of this server socket/socket.
 InputStream getInputStream()
          Returns an input stream for this socket.
 boolean getKeepAlive()
          Tests if SO_KEEPALIVE is enabled.
 java.net.InetAddress getLocalAddress()
          Gets the local address to which the socket is bound.
 int getLocalPort()
          Returns the port on which this socket is listening.
 java.net.SocketAddress getLocalSocketAddress()
          Returns the address of the endpoint this socket is bound to, or null if it is not bound yet.
 boolean getOOBInline()
          Tests if OOBINLINE is enabled.
 OutputStream getOutputStream()
          Returns an output stream for this socket.
 int getPort()
          Returns the remote port to which this socket is connected.
 SocketInterface.TcpSocketInterface getProxy()
          Returns the entity reference to the socket itself.
 int getReceiveBufferSize()
          Gets the value of the SO_RCVBUF option for this ServerSocket, that is the proposed buffer size that will be used for Sockets accepted from this ServerSocket.
 java.net.SocketAddress getRemoteSocketAddress()
          Returns the address of the endpoint this socket is connected to, or null if it is unconnected.
 boolean getReuseAddress()
          Tests if SO_REUSEADDR is enabled.
 int getSendBufferSize()
          Get value of the SO_SNDBUF option for this Socket, that is the buffer size used by the platform for output on this Socket.
 int getSoLinger()
          Returns setting for SO_LINGER.
 int getSoTimeout()
          Retrieve setting for SO_TIMEOUT.
 boolean getTcpNoDelay()
          Tests if TCP_NODELAY is enabled.
 int getTrafficClass()
          Gets traffic class or type-of-service in the IP header for packets sent from this Socket.
private  void initializeAll(java.net.InetAddress rAddr, int rPort, java.net.InetAddress lAddr, int lPort, boolean doConnect)
          Initialize all variables needed.
private  void initializeSocketVariables()
          Initialize all the socket variables.
private  void initializeTCPBuffers()
          Initialize all buffers needed for TCP implementation.
private  void initializeTCPVariables()
          Initialize all variables needed for TCP Implementation.
private  void initializeTimerVariables()
          Initialize all variables needed for TCP timers.
private  void initiateClosingConnection()
          this method is called to close the connection.
private  boolean isAcceptableACK(TransTcp.TcpMessage msg)
          Check if the ACK packet received is acknowledging the data that have not been acknowledged.
 boolean isBound()
          Returns the binding state of the ServerSocket.
 boolean isClosed()
          Returns the closed state of the ServerSocket.
 boolean isConnected()
          Returns the connection state of the socket.
 boolean isInputShutdown()
          Returns wether the read-half of the socket connection is closed.
 boolean isOutputShutdown()
          Returns wether the write-half of the socket connection is closed.
private  boolean isPacketOutofWindow(TransTcp.TcpMessage msg)
          Check if the incoming packet is out of receiving window.
private  void onClosedState(TransTcp.TcpMessage msg, NetAddress src)
          This method takes care of all the steps that need to be done if we receive a packet during CLOSED state.
private  void onClosingState(TransTcp.TcpMessage msg)
          This method takes care of all the steps that need to be done if we receive a packet during CLOSING state.
private  void onEstablishedState(TransTcp.TcpMessage msg)
          This method takes care of all the steps that need to be done if we receive a packet during ESTABLISHED state.
private  void onFinWait1State(TransTcp.TcpMessage msg)
          This method takes care of all the steps that need to be done if we receive a packet during FIN_WAIT_1 state.
private  void onFinWait2State(TransTcp.TcpMessage msg)
          This method takes care of all the steps that need to be done if we receive a packet during FIN_WAIT_2 state.
private  void onLastAckState(TransTcp.TcpMessage msg)
          This method takes care of all the steps that need to be done if we receive a packet during LAST_ACK state.
private  void onReceiveACK(TransTcp.TcpMessage msg)
          This method handles the case when ACK packet is received.
private  void onReceiveData(TransTcp.TcpMessage msg)
          This method handles the case when data packet is received.
private  void onReceiveValidDataorACK(TransTcp.TcpMessage msg)
          This method is to check if receive data packet or ACK packet.
private  boolean onRetransmit(int seqNumToSend)
          Called when retransmission happens.
private  void onSynReceivedState(TransTcp.TcpMessage msg)
          This method takes care of all the steps that need to be done if we receive a packet during SYN_RECEIVED state.
private  void onSynSentState(TransTcp.TcpMessage msg)
          This method takes care of all the steps that need to be done if we receive a packet during SYN_SENT state.
 void persistTimerTimeout(int timerId, int seqNum)
          Execution when persist timer times out (sending probe message).
protected  void printMessage(TransTcp.TcpMessage msg, boolean isReceive)
          Prints out the message header and payload.
 int queueBytes(byte[] data)
          This method is called to send bytes to the other side.
 void resetTimerTimeout(int timerId)
          Execution when reset timer times out (closing the socket).
 void retransmitTimerTimeout(int seqNum, long time)
          Attempt to retransmit because the timer times out.
private  void sendBytesInBuffer()
          This method is called to send bytes in the buffer until they fill the receiver window.
private  void sendBytesToChannel(int length)
          This method sends bytes to channel.
protected  TransTcp.TcpMessage sendDataPacket(byte[] data)
          Send a packet to the remote socket.
protected  void sendFINPacket()
          A method to send FIN packet.
protected  void sendFirstACKPacket()
          A method to send ACK packet.
private  void sendMessage(TransTcp.TcpMessage msg)
          Send a TCP message to remote socket.
protected  void sendRSTPacket(int seqNum, int ackNum)
          A method to send RST packet.
protected  void sendSYNACKPacket()
          A method to send SYNACK packet.
protected  void sendSYNPacket()
          A method to send SYN packet.
 void sendUrgentData(int data)
          Send one byte of urgent data on the socket.
private  void setInitAckNum(int ackNum)
          Set the initial acknowledgement number for this socket.
 void setKeepAlive(boolean on)
          Enable/disable SO_KEEPALIVE.
private  void setLocalAddress(java.net.InetAddress address, int port)
          Set the local address and local port for this socket.
 void setOOBInline(boolean on)
          Enable/disable OOBINLINE (receipt of TCP urgent data) By default, this option is disabled and TCP urgent data received on a socket is silently discarded.
 void setReceiveBufferSize(int size)
          Sets a default proposed value for the SO_RCVBUF option for sockets accepted from this ServerSocket.
private  void setRemoteAddress(java.net.InetAddress address, int port)
          Set the remote address and remote port for this socket.
 void setReuseAddress(boolean on)
          Enable/disable the SO_REUSEADDR socket option.
 void setSendBufferSize(int size)
          Sets the SO_SNDBUF option to the specified value for this Socket.
static void setSocketImplFactory(java.net.SocketImplFactory fac)
          Sets the client socket implementation factory for the application.
 void setSoLinger(boolean on, int linger)
          Enable/disable SO_LINGER with the specified linger time in seconds.
 void setSoTimeout(int timeout)
          Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.
 void setTcpEntity(TransInterface.TransTcpInterface tcpEntity)
          Sets the reference to the network layer.
 void setTcpNoDelay(boolean on)
          Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm).
 void setTrafficClass(int tc)
          Sets traffic class or type-of-service octet in the IP header for packets sent from this Socket.
 void shutdownInput()
          Places the input stream for this socket at "end of stream".
 void shutdownOutput()
          Disables the output stream for this socket.
private  void SlowStart()
          This method implements Start phase for congestion control.
 void startPersistTimer(int seqNum)
          Methods for persist timer (sender sending packets to probe receiver window).
 void startResetTimer()
          Methods for reset timer (this timer is used when establishing or closing connection --> If no reply is received, connection is reset).
 void startRetransmitTimer(int seqNum, long time)
          Schedule a retransmission for a message.
 void startTimeWaitTimer()
          Methods for timer during TIME_WAIT state.
 void timeWaitTimerTimeout()
          Execution when time wait timer times out (closing the socket).
 java.lang.String toString()
          Returns the implementation address and implementation port of this socket as a String.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

OFF

public static final int OFF
Debug printing flag. OFF = no debug output

See Also:
Constant Field Values

INFO

public static final int INFO
Debug printing flag. INFO = minimum debug output

See Also:
Constant Field Values

TCP_DEBUG

public static final int TCP_DEBUG
Debug printing flag. TCP_DEBUG = debug output, showing only packet traffic

See Also:
Constant Field Values

FULL_DEBUG

public static final int FULL_DEBUG
Debug printing flag. FULL_DEBUG = full debug output

See Also:
Constant Field Values

PRINTOUT

public static final int PRINTOUT
Indicator for printing debug outputs.

See Also:
Constant Field Values

MSS

public static final int MSS
Maximum Segment Size. Number of bytes to transfer in one packet.

See Also:
Constant Field Values

MSL

public static final int MSL
Maximum Segment Lifetime. Maximum amount of time any segment can exist in the network before being discarded. (Can be 30 seconds, 1 minute, or 2 minutes) (TCP has to wait for 2*MSL before the socket pair (client IP address, client port number, server IP address, and server port number) can be reused)

See Also:
Constant Field Values

DELAYED_ACK_TIME

public static final long DELAYED_ACK_TIME
Number of milliseconds to wait before sending an ACK.

See Also:
Constant Field Values

RETRANSMIT_TIMEOUT

public static final long RETRANSMIT_TIMEOUT
Number of seconds to wait for first retransmission timer.

See Also:
Constant Field Values

RETRANSMIT_TIMEOUT_FINAL

public static final long RETRANSMIT_TIMEOUT_FINAL
Number of seconds to wait for second retransmission timer.

See Also:
Constant Field Values

PERSIST_TIMER

public static final long PERSIST_TIMER
Number of seconds to wait before sending probe packets. This happens when receiver is advertising zero window.

See Also:
Constant Field Values

INIT_WINDOW_SIZE

public static final short INIT_WINDOW_SIZE
Initial window size.

See Also:
Constant Field Values

self

private SocketInterface.TcpSocketInterface self
A pointer to this socket's proxy.


lport

private int lport
Local port number for the connection.


rport

private int rport
Remote port number for the connection.


laddr

private NetAddress laddr
Local address for the connection.


raddr

private NetAddress raddr
Remote address for the connection.


channel

private Channel channel
A channel for blocking send/receive.


callback

private TransInterface.SocketHandler.TcpHandler callback
A callback object used by other entities to call this socket.


tcpEntity

private TransInterface.TransTcpInterface tcpEntity
A reference to TCP Entity.


isBound

private boolean isBound
booleans to support socket implementation.


isClosed

private boolean isClosed
booleans to support socket implementation.


isConnected

private boolean isConnected
booleans to support socket implementation.


isTcpNoDelay

private boolean isTcpNoDelay
booleans to support socket implementation.


in

private TcpInputStream in
Input Stream for this connection.


out

private TcpOutputStream out
Output Stream for this connection.


connectInConstructor

private boolean connectInConstructor
booleans to support TCP implementation.


isClosing

private boolean isClosing
booleans to support TCP implementation.


isApplicationWaiting

private boolean isApplicationWaiting
flag to note if application layer is waiting for messages.


numBytesRequest

private int numBytesRequest
number of bytes requested by application layer while waiting.


currentState

private int currentState
State of the TCP connection. (See Constants.java for details)


receiveBuffer

private CircularBuffer receiveBuffer
Buffers to hold bytes received.


sendBuffer

private CircularBuffer sendBuffer
Buffers to hold bytes to be sent.


initSeqNum

private int initSeqNum
Initial sequence number.


initAckNum

private int initAckNum
Initial acknowledgement number.


snd_nxt

private int snd_nxt
next sequence number to be sent.


snd_una

private int snd_una
oldest unacknowledged sequence number.


rwnd

private short rwnd
most recently advertised receiver window.


cwnd

private short cwnd
congestion window.


cwnd_increment

private double cwnd_increment
to hold the increment of congestion window during congestion avoidance.


sshtresh

private short sshtresh
threshold for slow start/congestion avoidance.


dupAckCounter

private int dupAckCounter
counter for number of duplicate ACKs that we currently receive.


probeMessage

private TransTcp.TcpMessage probeMessage
temporary variable to store the current probe message (if not null).


rList

private PriorityList rList
a list to hold packets that might need to be retransmitted.


rMsgBuffer

private PriorityList rMsgBuffer
a list to hold out-of-order received packets that are in window.


rcv_nxt

private int rcv_nxt
next sequence number expected on an incoming segment.


rcv_wnd

private short rcv_wnd
receiver window.


temp_rcv_wnd

private short temp_rcv_wnd
temporary receiver window (used to hold update after some data are sent to application layer).


last_adv_wnd

private short last_adv_wnd
the receiving window that we most recently advertised.


probeCounter

private int probeCounter
to count how many probes we have received for this current session (session means the time when the receiver advertises zero window).


persistTimerId

private int persistTimerId
ID for persist timer.


resetTimerId

private int resetTimerId
ID for reset timer (for special cases).


packetCounter

private int packetCounter
Number of packets sent by the socket.

Constructor Detail

TcpSocket

public TcpSocket()
Creates an unconnected socket, with the system-default type of SocketImpl.


TcpSocket

public TcpSocket(java.net.InetAddress address,
                 int port)
Creates a stream socket and connects it to the specified port number at the specified IP address.

Parameters:
address - the IP address
port - the port number

TcpSocket

public TcpSocket(java.net.InetAddress host,
                 int port,
                 boolean stream)
Deprecated. Use DatagramSocket instead for UDP transport.

Parameters:
host - the IP address
port - the port number
stream - if true, create a stream socket; otherwise, create a datagram socket.

TcpSocket

public TcpSocket(java.net.InetAddress address,
                 int port,
                 java.net.InetAddress localAddr,
                 int localPort)
Creates a socket and connects it to the specified remote address on the specified remote port.

Parameters:
address - the remote address
port - the remote port
localAddr - the local address the socket is bound to
localPort - the local port the socket is bound to

TcpSocket

protected TcpSocket(java.net.SocketImpl impl)
Creates an unconnected Socket with a user-specified SocketImpl.

Parameters:
impl - an instance of a SocketImpl the subclass wishes to use on the Socket

TcpSocket

protected TcpSocket(TransInterface.TransTcpInterface tcpEntity,
                    java.net.InetAddress rAddr,
                    short rPort,
                    java.net.InetAddress lAddr,
                    short lPort,
                    int initialAckNum,
                    short winSize)
Creates an unconnected Socket with a user-specified TransInterface Entity and SYN packet received by TcpServerSocket.

Parameters:
tcpEntity - entity reference to transport layer
rAddr - remote address
rPort - remote port number
lAddr - local address
lPort - local port number
initialAckNum - initial acknowledgement number
winSize - the other side's receiver window size

TcpSocket

public TcpSocket(java.lang.String host,
                 int port)
Creates a stream socket and connects it to the specified port number on the named host.

Parameters:
host - the host name, or null for the loopback address.
port - the port number.

TcpSocket

public TcpSocket(java.lang.String host,
                 int port,
                 boolean stream)
Deprecated. Use DatagramSocket instead for UDP transport.

Parameters:
host - the host name, or null for the loopback address.
port - the port number.
stream - a boolean indicating whether this is a stream socket or a datagram socket.

TcpSocket

public TcpSocket(java.lang.String host,
                 int port,
                 java.net.InetAddress localAddr,
                 int localPort)
Creates a socket and connects it to the specified remote host on the specified remote port.

Parameters:
host - the name of the remote host, or null for the loopback address.
port - the remote port
localAddr - the local address the socket is bound to
localPort - the local port the socket is bound to
Method Detail

createProxy

public void createProxy()
Create an entity reference to itself.


getProxy

public SocketInterface.TcpSocketInterface getProxy()
Returns the entity reference to the socket itself.

Returns:
Entity reference to TcpSocket

setTcpEntity

public void setTcpEntity(TransInterface.TransTcpInterface tcpEntity)
Sets the reference to the network layer.

Specified by:
setTcpEntity in interface SocketInterface
Parameters:
tcpEntity - entity reference to transport layer

_jistPostInit

public void _jistPostInit()
Post-constructor call. Since constructors can not be blocking (JiST/Java limitation), we rewrite a regular socket constructor to two calls. This is the second one, and it can be blocking, because it is a regular method.

Specified by:
_jistPostInit in interface SocketInterface

bind

public void bind(java.net.SocketAddress bindpoint)
Binds the ServerSocket to a specific address (IP address and port number).

Specified by:
bind in interface SocketInterface
Parameters:
bindpoint - The IP address & port number to bind to.

close

public void close()
Closes this socket.

Specified by:
close in interface SocketInterface

connect

public void connect(java.net.SocketAddress endpoint)
Connects this socket to the server.

Specified by:
connect in interface SocketInterface.TcpSocketInterface
Parameters:
endpoint - the SocketAddress

connect

public void connect(java.net.SocketAddress endpoint,
                    int timeout)
Connects this socket to the server with a specified timeout value.

Specified by:
connect in interface SocketInterface.TcpSocketInterface
Parameters:
endpoint - the SocketAddress
timeout - the timeout value to be used in milliseconds

connect

private void connect(java.net.InetAddress raddr,
                     int rport,
                     int timeout)
Connects this socket to a specified address and timeout value.

Parameters:
raddr - remote address
rport - remote port
timeout - the timeout value to be used in milliseconds

getChannel

public java.nio.channels.SocketChannel getChannel()
Returns the unique SocketChannel object associated with this socket, if any.

Specified by:
getChannel in interface SocketInterface.TcpSocketInterface
Returns:
the socket channel associated with this socket, or null if this socket was not created for a channel

getInetAddress

public java.net.InetAddress getInetAddress()
Returns the local address of this server socket/socket.

Specified by:
getInetAddress in interface SocketInterface
Returns:
the address to which this socket is bound, or null if the socket is unbound.

getInputStream

public InputStream getInputStream()
Returns an input stream for this socket.

Specified by:
getInputStream in interface SocketInterface.TcpSocketInterface
Returns:
an input stream for reading bytes from this socket.

getKeepAlive

public boolean getKeepAlive()
Tests if SO_KEEPALIVE is enabled.

Specified by:
getKeepAlive in interface SocketInterface.TcpSocketInterface
Returns:
a boolean indicating whether or not SO_KEEPALIVE is enabled.

getLocalAddress

public java.net.InetAddress getLocalAddress()
Gets the local address to which the socket is bound.

Specified by:
getLocalAddress in interface SocketInterface.TcpSocketInterface
Returns:
the local address to which the socket is bound or InetAddress.anyLocalAddress() if the socket is not bound yet.

getLocalPort

public int getLocalPort()
Returns the port on which this socket is listening.

Specified by:
getLocalPort in interface SocketInterface
Returns:
the port number to which this socket is listening or -1 if the socket is not bound yet.

getLocalSocketAddress

public java.net.SocketAddress getLocalSocketAddress()
Returns the address of the endpoint this socket is bound to, or null if it is not bound yet.

Specified by:
getLocalSocketAddress in interface SocketInterface
Returns:
a SocketAddress representing the local endpoint of this socket, or null if it is not bound yet.

getOOBInline

public boolean getOOBInline()
Tests if OOBINLINE is enabled.

Specified by:
getOOBInline in interface SocketInterface.TcpSocketInterface
Returns:
a boolean indicating whether or not OOBINLINE is enabled.

getOutputStream

public OutputStream getOutputStream()
Returns an output stream for this socket.

Specified by:
getOutputStream in interface SocketInterface.TcpSocketInterface
Returns:
an output stream for writing bytes to this socket.

getPort

public int getPort()
Returns the remote port to which this socket is connected.

Specified by:
getPort in interface SocketInterface.TcpSocketInterface
Returns:
the remote port number to which this socket is connected, or 0 if the socket is not connected yet.

getReceiveBufferSize

public int getReceiveBufferSize()
Gets the value of the SO_RCVBUF option for this ServerSocket, that is the proposed buffer size that will be used for Sockets accepted from this ServerSocket.

Specified by:
getReceiveBufferSize in interface SocketInterface
Returns:
the value of the SO_RCVBUF option for this Socket.

getRemoteSocketAddress

public java.net.SocketAddress getRemoteSocketAddress()
Returns the address of the endpoint this socket is connected to, or null if it is unconnected.

Specified by:
getRemoteSocketAddress in interface SocketInterface.TcpSocketInterface
Returns:
a SocketAddress representing the local endpoint of this socket, or null if it is not bound yet.

getReuseAddress

public boolean getReuseAddress()
Tests if SO_REUSEADDR is enabled.

Specified by:
getReuseAddress in interface SocketInterface
Returns:
a boolean indicating whether or not SO_REUSEADDR is enabled.

getSendBufferSize

public int getSendBufferSize()
Get value of the SO_SNDBUF option for this Socket, that is the buffer size used by the platform for output on this Socket.

Specified by:
getSendBufferSize in interface SocketInterface.TcpSocketInterface
Returns:
the value of the SO_SNDBUF option for this Socket.

getSoLinger

public int getSoLinger()
Returns setting for SO_LINGER.

Specified by:
getSoLinger in interface SocketInterface.TcpSocketInterface
Returns:
the setting for SO_LINGER.

getSoTimeout

public int getSoTimeout()
Retrieve setting for SO_TIMEOUT.

Specified by:
getSoTimeout in interface SocketInterface
Returns:
the SO_TIMEOUT value

getTcpNoDelay

public boolean getTcpNoDelay()
Tests if TCP_NODELAY is enabled.

Specified by:
getTcpNoDelay in interface SocketInterface.TcpSocketInterface
Returns:
a boolean indicating whether or not TCP_NODELAY is enabled.

getTrafficClass

public int getTrafficClass()
Gets traffic class or type-of-service in the IP header for packets sent from this Socket.

Specified by:
getTrafficClass in interface SocketInterface.TcpSocketInterface
Returns:
the traffic class or type-of-service already set

isBound

public boolean isBound()
Returns the binding state of the ServerSocket.

Specified by:
isBound in interface SocketInterface
Returns:
true if the ServerSocket succesfuly bound to an address

isClosed

public boolean isClosed()
Returns the closed state of the ServerSocket.

Specified by:
isClosed in interface SocketInterface
Returns:
true if the socket has been closed

isConnected

public boolean isConnected()
Returns the connection state of the socket.

Specified by:
isConnected in interface SocketInterface.TcpSocketInterface
Returns:
true if the socket successfuly connected to a server

isInputShutdown

public boolean isInputShutdown()
Returns wether the read-half of the socket connection is closed.

Specified by:
isInputShutdown in interface SocketInterface.TcpSocketInterface
Returns:
true if the input of the socket has been shutdown

isOutputShutdown

public boolean isOutputShutdown()
Returns wether the write-half of the socket connection is closed.

Specified by:
isOutputShutdown in interface SocketInterface.TcpSocketInterface
Returns:
true if the output of the socket has been shutdown

sendUrgentData

public void sendUrgentData(int data)
Send one byte of urgent data on the socket.

Specified by:
sendUrgentData in interface SocketInterface.TcpSocketInterface
Parameters:
data - The byte of data to send

setKeepAlive

public void setKeepAlive(boolean on)
Enable/disable SO_KEEPALIVE.

Specified by:
setKeepAlive in interface SocketInterface.TcpSocketInterface
Parameters:
on - whether or not to have socket keep alive turned on

setOOBInline

public void setOOBInline(boolean on)
Enable/disable OOBINLINE (receipt of TCP urgent data) By default, this option is disabled and TCP urgent data received on a socket is silently discarded.

Specified by:
setOOBInline in interface SocketInterface.TcpSocketInterface
Parameters:
on - true to enable OOBINLINE, false to disable.

setReceiveBufferSize

public void setReceiveBufferSize(int size)
Sets a default proposed value for the SO_RCVBUF option for sockets accepted from this ServerSocket.

Specified by:
setReceiveBufferSize in interface SocketInterface
Parameters:
size - the size to which to set the receive buffer size. This value must be greater than 0.

setReuseAddress

public void setReuseAddress(boolean on)
Enable/disable the SO_REUSEADDR socket option.

Specified by:
setReuseAddress in interface SocketInterface
Parameters:
on - whether to enable or disable the socket option

setSendBufferSize

public void setSendBufferSize(int size)
Sets the SO_SNDBUF option to the specified value for this Socket.

Specified by:
setSendBufferSize in interface SocketInterface.TcpSocketInterface
Parameters:
size - the size to which to set the send buffer size. This value must be greater than 0.

setSocketImplFactory

public static void setSocketImplFactory(java.net.SocketImplFactory fac)
Sets the client socket implementation factory for the application.

Parameters:
fac - the desired factory

setSoLinger

public void setSoLinger(boolean on,
                        int linger)
Enable/disable SO_LINGER with the specified linger time in seconds.

Specified by:
setSoLinger in interface SocketInterface.TcpSocketInterface
Parameters:
on - whether or not to linger on.
linger - how long to linger for, if on is true.

setSoTimeout

public void setSoTimeout(int timeout)
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.

Specified by:
setSoTimeout in interface SocketInterface
Parameters:
timeout - the specified timeout, in milliseconds

setTcpNoDelay

public void setTcpNoDelay(boolean on)
Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm).

Specified by:
setTcpNoDelay in interface SocketInterface.TcpSocketInterface
Parameters:
on - true to enable TCP_NODELAY, false to disable.

setTrafficClass

public void setTrafficClass(int tc)
Sets traffic class or type-of-service octet in the IP header for packets sent from this Socket.

Specified by:
setTrafficClass in interface SocketInterface.TcpSocketInterface
Parameters:
tc - an int value for the bitset.

shutdownInput

public void shutdownInput()
                   throws java.io.IOException
Places the input stream for this socket at "end of stream".

Specified by:
shutdownInput in interface SocketInterface.TcpSocketInterface
Throws:
java.io.IOException - if an I/O error occurs when shutting down this socket.

shutdownOutput

public void shutdownOutput()
                    throws java.io.IOException
Disables the output stream for this socket.

Specified by:
shutdownOutput in interface SocketInterface.TcpSocketInterface
Throws:
java.io.IOException - if an I/O error occurs when shutting down this socket.

toString

public java.lang.String toString()
Returns the implementation address and implementation port of this socket as a String.

Specified by:
toString in interface SocketInterface
Overrides:
toString in class java.lang.Object
Returns:
a string representation of this socket.

setRemoteAddress

private void setRemoteAddress(java.net.InetAddress address,
                              int port)
Set the remote address and remote port for this socket.

Parameters:
address - remote address
port - remote port number

setLocalAddress

private void setLocalAddress(java.net.InetAddress address,
                             int port)
Set the local address and local port for this socket.

Parameters:
address - local address
port - local port number

initializeSocketVariables

private void initializeSocketVariables()
Initialize all the socket variables.


initializeTCPVariables

private void initializeTCPVariables()
Initialize all variables needed for TCP Implementation.


initializeTimerVariables

private void initializeTimerVariables()
Initialize all variables needed for TCP timers.


initializeTCPBuffers

private void initializeTCPBuffers()
Initialize all buffers needed for TCP implementation.


initializeAll

private void initializeAll(java.net.InetAddress rAddr,
                           int rPort,
                           java.net.InetAddress lAddr,
                           int lPort,
                           boolean doConnect)
Initialize all variables needed.

Parameters:
rAddr - remote address
rPort - remote port number
lAddr - local address
lPort - local port number
doConnect - set to true to try to connect in constructor

createStreams

private void createStreams()
Create the input and output streams for this socket.


establishingConnection

protected void establishingConnection()
this method is used to wait for incoming ACK packet for connection establishment.


initiateClosingConnection

private void initiateClosingConnection()
this method is called to close the connection.


setInitAckNum

private void setInitAckNum(int ackNum)
Set the initial acknowledgement number for this socket.

Parameters:
ackNum - acknowledgement number

printMessage

protected void printMessage(TransTcp.TcpMessage msg,
                            boolean isReceive)
Prints out the message header and payload.

Parameters:
msg - TCP message to print out
isReceive - true if printing for receiving side

getCurrentStateString

private java.lang.String getCurrentStateString()
Returns the string name of current state. (check Constants.java)

Returns:
string representation of current state

compareUnsignedShort

private int compareUnsignedShort(short a,
                                 short b)
Returns the difference between two unsigned shorts.

Parameters:
a - first short
b - second short
Returns:
a - b

compareUnsignedInt

private long compareUnsignedInt(int a,
                                int b)
Returns the difference between two unsigned integers.

Parameters:
a - first integer
b - second integer
Returns:
a - b

sendSYNPacket

protected void sendSYNPacket()
A method to send SYN packet.


sendSYNACKPacket

protected void sendSYNACKPacket()
A method to send SYNACK packet.


sendFirstACKPacket

protected void sendFirstACKPacket()
A method to send ACK packet.


sendFINPacket

protected void sendFINPacket()
A method to send FIN packet.


sendRSTPacket

protected void sendRSTPacket(int seqNum,
                             int ackNum)
A method to send RST packet.

Parameters:
seqNum - sequence number
ackNum - acknowledgement number

sendDataPacket

protected TransTcp.TcpMessage sendDataPacket(byte[] data)
Send a packet to the remote socket. To send an ACK packet, set data to null.

Parameters:
data - data to send
Returns:
sent packet

sendMessage

private void sendMessage(TransTcp.TcpMessage msg)
Send a TCP message to remote socket.

Parameters:
msg - message to send

sendBytesInBuffer

private void sendBytesInBuffer()
This method is called to send bytes in the buffer until they fill the receiver window. The bytes will be broken down to packets based on MSS (maximum segment size).


constructPackets

public void constructPackets()
Creates packets to be sent based on the receiver's advertised window (managing flow control).

Specified by:
constructPackets in interface SocketInterface.TcpSocketInterface

queueBytes

public int queueBytes(byte[] data)
This method is called to send bytes to the other side. What this method does is storing the bytes in the send buffer and then call sendPackets method to send the bytes.

Specified by:
queueBytes in interface SocketInterface.TcpSocketInterface
Parameters:
data - bytes to be stored in the send buffer
Returns:
the number of bytes actually stored

sendBytesToChannel

private void sendBytesToChannel(int length)
This method sends bytes to channel. The number of bytes to send is specified in the parameter.

Parameters:
length - number of bytes to send to application layer

getBytesFromSocket

public byte[] getBytesFromSocket(int length)
This method is called by the input stream to retrieve data from the transport layer.

Specified by:
getBytesFromSocket in interface SocketInterface.TcpSocketInterface
Parameters:
length - number of bytes to retrieve
Returns:
byte array containing data from socket

getCurrentReceiverWindow

private short getCurrentReceiverWindow()
Returns the smaller window (between the last advertised window and the congestion window) for the receiver.

Returns:
receiver window or congestion window, whichever is smaller.

startRetransmitTimer

public void startRetransmitTimer(int seqNum,
                                 long time)
Schedule a retransmission for a message.

Specified by:
startRetransmitTimer in interface SocketInterface.TcpSocketInterface
Parameters:
seqNum - sequence number of message to retransmit
time - wait time before attempting to retransmit

retransmitTimerTimeout

public void retransmitTimerTimeout(int seqNum,
                                   long time)
Attempt to retransmit because the timer times out.

Specified by:
retransmitTimerTimeout in interface SocketInterface.TcpSocketInterface
Parameters:
seqNum - sequence number of message to retransmit
time - wait time before attempting to retransmit

startPersistTimer

public void startPersistTimer(int seqNum)
Methods for persist timer (sender sending packets to probe receiver window).

Specified by:
startPersistTimer in interface SocketInterface.TcpSocketInterface
Parameters:
seqNum - number of the probe message

cancelPersistTimer

private void cancelPersistTimer()
Cancel the current persist timer.


persistTimerTimeout

public void persistTimerTimeout(int timerId,
                                int seqNum)
Execution when persist timer times out (sending probe message).

Specified by:
persistTimerTimeout in interface SocketInterface.TcpSocketInterface
Parameters:
timerId - ID of the persist timer
seqNum - number of the probe message

createProbeMessage

private boolean createProbeMessage()
Create a probe message (for persist timer) by extracting one byte of data from the send buffer.

Returns:
true if a probe message is available

startResetTimer

public void startResetTimer()
Methods for reset timer (this timer is used when establishing or closing connection --> If no reply is received, connection is reset).

Specified by:
startResetTimer in interface SocketInterface.TcpSocketInterface

cancelResetTimer

private void cancelResetTimer()
Cancel the current reset timer.


resetTimerTimeout

public void resetTimerTimeout(int timerId)
Execution when reset timer times out (closing the socket).

Specified by:
resetTimerTimeout in interface SocketInterface.TcpSocketInterface
Parameters:
timerId - ID of the reset timer

startTimeWaitTimer

public void startTimeWaitTimer()
Methods for timer during TIME_WAIT state.

Specified by:
startTimeWaitTimer in interface SocketInterface.TcpSocketInterface

timeWaitTimerTimeout

public void timeWaitTimerTimeout()
Execution when time wait timer times out (closing the socket).

Specified by:
timeWaitTimerTimeout in interface SocketInterface.TcpSocketInterface

checkPacketandState

public void checkPacketandState(TransTcp.TcpMessage msg,
                                NetAddress src)
Check and process the incoming packet depending on current state of the socket.

Specified by:
checkPacketandState in interface SocketInterface
Parameters:
msg - the incoming TCP message
src - source of packet

onClosedState

private void onClosedState(TransTcp.TcpMessage msg,
                           NetAddress src)
This method takes care of all the steps that need to be done if we receive a packet during CLOSED state.

Parameters:
msg - incoming packet
src - packet source

onSynSentState

private void onSynSentState(TransTcp.TcpMessage msg)
This method takes care of all the steps that need to be done if we receive a packet during SYN_SENT state.

Parameters:
msg - incoming packet

onSynReceivedState

private void onSynReceivedState(TransTcp.TcpMessage msg)
This method takes care of all the steps that need to be done if we receive a packet during SYN_RECEIVED state.

Parameters:
msg - incoming packet

onEstablishedState

private void onEstablishedState(TransTcp.TcpMessage msg)
This method takes care of all the steps that need to be done if we receive a packet during ESTABLISHED state.

Parameters:
msg - incoming packet

isPacketOutofWindow

private boolean isPacketOutofWindow(TransTcp.TcpMessage msg)
Check if the incoming packet is out of receiving window.

Parameters:
msg - incoming packet
Returns:
true if packet is out of receiving window

isAcceptableACK

private boolean isAcceptableACK(TransTcp.TcpMessage msg)
Check if the ACK packet received is acknowledging the data that have not been acknowledged.

Parameters:
msg - incoming packet
Returns:
true if ACK packet is acknowledging unacknowledged bytes

onReceiveValidDataorACK

private void onReceiveValidDataorACK(TransTcp.TcpMessage msg)
This method is to check if receive data packet or ACK packet. Then, the appropiate method is called to handle each case.

Parameters:
msg - incoming packet

onReceiveData

private void onReceiveData(TransTcp.TcpMessage msg)
This method handles the case when data packet is received. Will send ACK packet back, take care of probe messages, and send the data received to application layer if requested.

Parameters:
msg - incoming packet

onReceiveACK

private void onReceiveACK(TransTcp.TcpMessage msg)
This method handles the case when ACK packet is received. Will send more data or probe message (if advertised window is zero) and do congestion control algorithm.

Parameters:
msg - incoming packet

FastRetransmit

private void FastRetransmit()
This method implements Fast Retransmit algorithm.


SlowStart

private void SlowStart()
This method implements Start phase for congestion control.


CongestionAvoidance

private void CongestionAvoidance()
This method implements Congestion Avoidance phase for congestion control.


onRetransmit

private boolean onRetransmit(int seqNumToSend)
Called when retransmission happens. Parameter is to denote which message to send.

Parameters:
seqNumToSend - sequence number of the packet to be retransmitted
Returns:
true if the message is retransmitted, false otherwise.

onFinWait1State

private void onFinWait1State(TransTcp.TcpMessage msg)
This method takes care of all the steps that need to be done if we receive a packet during FIN_WAIT_1 state.

Parameters:
msg - incoming packet

onFinWait2State

private void onFinWait2State(TransTcp.TcpMessage msg)
This method takes care of all the steps that need to be done if we receive a packet during FIN_WAIT_2 state.

Parameters:
msg - incoming packet

onClosingState

private void onClosingState(TransTcp.TcpMessage msg)
This method takes care of all the steps that need to be done if we receive a packet during CLOSING state.

Parameters:
msg - incoming packet

onLastAckState

private void onLastAckState(TransTcp.TcpMessage msg)
This method takes care of all the steps that need to be done if we receive a packet during LAST_ACK state.

Parameters:
msg - incoming packet

closeSocket

private void closeSocket(boolean doUnbind)
This method is called when socket is to be closed. (also unbind from current port).

Parameters:
doUnbind - set to true to unbind from current port when closing socket.