INET Framework for OMNeT++/OMNEST
TCPSocket Class Reference

#include <TCPSocket.h>

List of all members.

Classes

class  CallbackInterface

Public Types

enum  State {
  NOT_BOUND, BOUND, LISTENING, CONNECTING,
  CONNECTED, PEER_CLOSED, LOCALLY_CLOSED, CLOSED,
  SOCKERROR
}

Public Member Functions

 TCPSocket ()
 TCPSocket (cMessage *msg)
 ~TCPSocket ()
int getConnectionId () const
int getState ()
Getter functions
IPvXAddress getLocalAddress ()
int getLocalPort ()
IPvXAddress getRemoteAddress ()
int getRemotePort ()
Opening and closing connections, sending data
void setOutputGate (cGate *toTcp)
void bind (int localPort)
void bind (IPvXAddress localAddr, int localPort)
const char * getSendQueueClass () const
const char * getReceiveQueueClass () const
const char * getTCPAlgorithmClass () const
void setSendQueueClass (const char *sendQueueClass)
void setReceiveQueueClass (const char *receiveQueueClass)
void setTCPAlgorithmClass (const char *tcpAlgorithmClass)
void listen ()
void listenOnce ()
void connect (IPvXAddress remoteAddr, int remotePort)
void send (cMessage *msg)
void close ()
void abort ()
void requestStatus ()
void renewSocket ()

Static Public Member Functions

static const char * stateName (int state)

Protected Member Functions

void sendToTCP (cMessage *msg)
void listen (bool fork)

Protected Attributes

int connId
int sockstate
IPvXAddress localAddr
int localPrt
IPvXAddress remoteAddr
int remotePrt
CallbackInterfacecb
void * yourPtr
cGate * gateToTcp
std::string sendQueueClass
std::string receiveQueueClass
std::string tcpAlgorithmClass

Handling of messages arriving from TCP

bool belongsToSocket (cMessage *msg)
void setCallbackObject (CallbackInterface *cb, void *yourPtr=NULL)
void processMessage (cMessage *msg)
static bool belongsToAnyTCPSocket (cMessage *msg)

Detailed Description

TCPSocket is a convenience class, to make it easier to manage TCP connections from your application models. You'd have one (or more) TCPSocket object(s) in your application simple module class, and call its member functions (bind(), listen(), connect(), etc.) to open, close or abort a TCP connection.

TCPSocket chooses and remembers the connId for you, assembles and sends command packets (such as OPEN_ACTIVE, OPEN_PASSIVE, CLOSE, ABORT, etc.) to TCP, and can also help you deal with packets and notification messages arriving from TCP.

A session which opens a connection from local port 1000 to 10.0.0.2:2000, sends 16K of data and closes the connection may be as simple as this (the code can be placed in your handleMessage() or activity()):

   TCPSocket socket;
   socket.connect(IPvXAddress("10.0.0.2"), 2000);
   msg = new cMessage("data1");
   msg->setByteLength(16*1024);  // 16K
   socket.send(msg);
   socket.close();
 

Dealing with packets and notification messages coming from TCP is somewhat more cumbersome. Basically you have two choices: you either process those messages yourself, or let TCPSocket do part of the job. For the latter, you give TCPSocket a callback object on which it'll invoke the appropriate member functions: socketEstablished(), socketDataArrived(), socketFailure(), socketPeerClosed(), etc (these are methods of TCPSocket::CallbackInterface)., The callback object can be your simple module class too.

This code skeleton example shows how to set up a TCPSocket to use the module itself as callback object:

 class MyModule : public cSimpleModule, public TCPSocket::CallbackInterface
 {
     TCPSocket socket;
     virtual void socketDataArrived(int connId, void *yourPtr, cPacket *msg, bool urgent);
     virtual void socketFailure(int connId, void *yourPtr, int code);
     ...
 };
 void MyModule::initialize() {
     socket.setCallbackObject(this,NULL);
 }
 void MyModule::handleMessage(cMessage *msg) {
     if (socket.belongsToSocket(msg))
         socket.processMessage(msg); // dispatch to socketXXXX() methods
     else
         ...
 }
 void MyModule::socketDataArrived(int, void *, cPacket *msg, bool) {
     ev << "Received TCP data, " << msg->getByteLength() << " bytes\\n";
     delete msg;
 }
 void MyModule::socketFailure(int, void *, int code) {
     if (code==TCP_I_CONNECTION_RESET)
         ev << "Connection reset!\\n";
     else if (code==TCP_I_CONNECTION_REFUSED)
         ev << "Connection refused!\\n";
     else if (code==TCP_I_TIMEOUT)
         ev << "Connection timed out!\\n";
 }
 

If you need to manage a large number of sockets (e.g. in a server application which handles multiple incoming connections), the TCPSocketMap class may be useful. The following code fragment to handle incoming connections is from the LDP module:

 TCPSocket *socket = socketMap.findSocketFor(msg);
 if (!socket)
 {
     // not yet in socketMap, must be new incoming connection: add to socketMap
     socket = new TCPSocket(msg);
     socket->setOutputGate(gate("tcpOut"));
     socket->setCallbackObject(this, NULL);
     socketMap.addSocket(socket);
 }
 // dispatch to socketEstablished(), socketDataArrived(), socketPeerClosed()
 // or socketFailure()
 socket->processMessage(msg);
 
See also:
TCPSocketMap

Member Enumeration Documentation

Enumerator:
NOT_BOUND 
BOUND 
LISTENING 
CONNECTING 
CONNECTED 
PEER_CLOSED 
LOCALLY_CLOSED 
CLOSED 
SOCKERROR 

Constructor & Destructor Documentation

TCPSocket::TCPSocket ( )

Constructor. The getConnectionId() method returns a valid Id right after constructor call.

{
    // don't allow user-specified connIds because they may conflict with
    // automatically assigned ones.
    connId = ev.getUniqueNumber();
    sockstate = NOT_BOUND;

    localPrt = remotePrt = -1;
    cb = NULL;
    yourPtr = NULL;

    gateToTcp = NULL;
}
TCPSocket::TCPSocket ( cMessage *  msg)

Constructor, to be used with forked sockets (see listen()). The new connId will be picked up from the message: it should have arrived from TCP and contain TCPCommmand control info.

{
    TCPCommand *ind = dynamic_cast<TCPCommand *>(msg->getControlInfo());
    if (!ind)
        opp_error("TCPSocket::TCPSocket(cMessage *): no TCPCommand control info in message (not from TCP?)");

    connId = ind->getConnId();
    sockstate = CONNECTED;

    localPrt = remotePrt = -1;
    cb = NULL;
    yourPtr = NULL;

    gateToTcp = NULL;

    if (msg->getKind()==TCP_I_ESTABLISHED)
    {
        // management of stockstate is left to processMessage() so we always
        // set it to CONNECTED in the ctor, whatever TCP_I_xxx arrives.
        // However, for convenience we extract TCPConnectInfo already here, so that
        // remote address/port can be read already after the ctor call.

        TCPConnectInfo *connectInfo = dynamic_cast<TCPConnectInfo *>(msg->getControlInfo());
        localAddr = connectInfo->getLocalAddr();
        remoteAddr = connectInfo->getRemoteAddr();
        localPrt = connectInfo->getLocalPort();
        remotePrt = connectInfo->getRemotePort();
    }
}
TCPSocket::~TCPSocket ( ) [inline]

Destructor

{}

Member Function Documentation

void TCPSocket::abort ( )

Aborts the connection.

{
    if (sockstate!=NOT_BOUND && sockstate!=BOUND && sockstate!=CLOSED && sockstate!=SOCKERROR)
    {
        cMessage *msg = new cMessage("ABORT", TCP_C_ABORT);
        TCPCommand *cmd = new TCPCommand();
        cmd->setConnId(connId);
        msg->setControlInfo(cmd);
        sendToTCP(msg);
    }
    sockstate = CLOSED;
}
bool TCPSocket::belongsToAnyTCPSocket ( cMessage *  msg) [static]

Returns true if the message belongs to any TCPSocket instance. (This basically checks if the message has a TCPCommand attached to it as getControlInfo().)

{
    return dynamic_cast<TCPCommand *>(msg->getControlInfo());
}
bool TCPSocket::belongsToSocket ( cMessage *  msg)

Returns true if the message belongs to this socket instance (message has a TCPCommand as getControlInfo(), and the connId in it matches that of the socket.)

Referenced by processMessage().

{
    return dynamic_cast<TCPCommand *>(msg->getControlInfo()) &&
           ((TCPCommand *)(msg->getControlInfo()))->getConnId()==connId;
}
void TCPSocket::bind ( int  localPort)

Bind the socket to a local port number.

Referenced by TCPSessionApp::activity(), TCPSrvHostApp::initialize(), TCPSinkApp::initialize(), TCPGenericSrvApp::initialize(), TCPGenericCliAppBase::initialize(), TCPEchoApp::initialize(), LDP::initialize(), and LDP::openTCPConnectionToPeer().

{
    if (sockstate!=NOT_BOUND)
        opp_error("TCPSocket::bind(): socket already bound");
    if (lPort<0 || lPort>65535)
        opp_error("TCPSocket::bind(): invalid port number %d", lPort);

    localPrt = lPort;
    sockstate = BOUND;
}
void TCPSocket::bind ( IPvXAddress  localAddr,
int  localPort 
)

Bind the socket to a local port number and IP address (useful with multi-homing).

{
    if (sockstate!=NOT_BOUND)
        opp_error("TCPSocket::bind(): socket already bound");
    // allow -1 here, to make it possible to specify address only
    if ((lPort<0 || lPort>65535) && lPort!=-1)
        opp_error("TCPSocket::bind(): invalid port number %d", lPort);

    localAddr = lAddr;
    localPrt = lPort;
    sockstate = BOUND;
}
void TCPSocket::close ( )

Closes the local end of the connection. With TCP, a CLOSE operation means "I have no more data to send", and thus results in a one-way connection until the remote TCP closes too (or the FIN_WAIT_1 timeout expires)

Referenced by TCPSessionApp::activity(), TCPGenericCliAppBase::close(), and TCPGenericSrvThread::dataArrived().

{
    if (sockstate!=CONNECTED && sockstate!=PEER_CLOSED && sockstate!=CONNECTING && sockstate!=LISTENING)
        opp_error("TCPSocket::close(): not connected or close() already called");

    cMessage *msg = new cMessage("CLOSE", TCP_C_CLOSE);
    TCPCommand *cmd = new TCPCommand();
    cmd->setConnId(connId);
    msg->setControlInfo(cmd);
    sendToTCP(msg);
    sockstate = sockstate==CONNECTED ? LOCALLY_CLOSED : CLOSED;
}
void TCPSocket::connect ( IPvXAddress  remoteAddr,
int  remotePort 
)

Active OPEN to the given remote socket.

Referenced by TCPSessionApp::activity(), TCPGenericCliAppBase::connect(), and LDP::openTCPConnectionToPeer().

{
    if (sockstate!=NOT_BOUND && sockstate!=BOUND)
        opp_error( "TCPSocket::connect(): connect() or listen() already called (need renewSocket()?)");
    if (remotePort<0 || remotePort>65535)
        opp_error("TCPSocket::connect(): invalid remote port number %d", remotePort);

    cMessage *msg = new cMessage("ActiveOPEN", TCP_C_OPEN_ACTIVE);

    remoteAddr = remoteAddress;
    remotePrt = remotePort;

    TCPOpenCommand *openCmd = new TCPOpenCommand();
    openCmd->setConnId(connId);
    openCmd->setLocalAddr(localAddr);
    openCmd->setLocalPort(localPrt);
    openCmd->setRemoteAddr(remoteAddr);
    openCmd->setRemotePort(remotePrt);
    openCmd->setSendQueueClass(sendQueueClass.c_str());
    openCmd->setReceiveQueueClass(receiveQueueClass.c_str());
    openCmd->setTcpAlgorithmClass(tcpAlgorithmClass.c_str());

    msg->setControlInfo(openCmd);
    sendToTCP(msg);
    sockstate = CONNECTING;
}
int TCPSocket::getConnectionId ( ) const [inline]

Returns the internal connection Id. TCP uses the (gate index, connId) pair to identify the connection when it receives a command from the application (or TCPSocket).

Referenced by TCPSocketMap::addSocket(), and TCPSocketMap::removeSocket().

{return connId;}
IPvXAddress TCPSocket::getLocalAddress ( ) [inline]
{return localAddr;}
int TCPSocket::getLocalPort ( ) [inline]
{return localPrt;}
const char* TCPSocket::getReceiveQueueClass ( ) const [inline]

Returns the current receiveQueueClass parameter.

{return receiveQueueClass.c_str();}
IPvXAddress TCPSocket::getRemoteAddress ( ) [inline]

Referenced by LDP::processMessageFromTCP().

{return remoteAddr;}
int TCPSocket::getRemotePort ( ) [inline]
{return remotePrt;}
const char* TCPSocket::getSendQueueClass ( ) const [inline]

Returns the current sendQueueClass parameter.

{return sendQueueClass.c_str();}
int TCPSocket::getState ( ) [inline]

Returns the socket state, one of NOT_BOUND, CLOSED, LISTENING, CONNECTING, CONNECTED, etc. Messages received from TCP must be routed through processMessage() in order to keep socket state up-to-date.

Referenced by TCPSessionApp::activity(), operator<<(), and TCPGenericCliAppBase::socketPeerClosed().

{return sockstate;}
const char* TCPSocket::getTCPAlgorithmClass ( ) const [inline]

Returns the current tcpAlgorithmClass parameter.

{return tcpAlgorithmClass.c_str();}
void TCPSocket::listen ( ) [inline]

Initiates passive OPEN, creating a "forking" connection that will listen on the port you bound the socket to. Every incoming connection will get a new connId (and thus, must be handled with a new TCPSocket object), while the original connection (original connId) will keep listening on the port. The new TCPSocket object must be created with the TCPSocket(cMessage *msg) constructor.

If you need to handle multiple incoming connections, the TCPSocketMap class can also be useful, and TCPSrvHostApp shows how to put it all together. See also TCPOpenCommand documentation (neddoc) for more info.

Referenced by listen().

{listen(true);}
void TCPSocket::listen ( bool  fork) [protected]

Referenced by TCPSrvHostApp::initialize(), TCPSinkApp::initialize(), TCPGenericSrvApp::initialize(), TCPEchoApp::initialize(), and LDP::initialize().

{
    if (sockstate!=BOUND)
        opp_error(sockstate==NOT_BOUND ? "TCPSocket: must call bind() before listen()"
                                       : "TCPSocket::listen(): connect() or listen() already called");

    cMessage *msg = new cMessage("PassiveOPEN", TCP_C_OPEN_PASSIVE);

    TCPOpenCommand *openCmd = new TCPOpenCommand();
    openCmd->setLocalAddr(localAddr);
    openCmd->setLocalPort(localPrt);
    openCmd->setConnId(connId);
    openCmd->setFork(fork);
    openCmd->setSendQueueClass(sendQueueClass.c_str());
    openCmd->setReceiveQueueClass(receiveQueueClass.c_str());
    openCmd->setTcpAlgorithmClass(tcpAlgorithmClass.c_str());

    msg->setControlInfo(openCmd);
    sendToTCP(msg);
    sockstate = LISTENING;
}
void TCPSocket::listenOnce ( ) [inline]

Initiates passive OPEN to create a non-forking listening connection. Non-forking means that TCP will accept the first incoming connection, and refuse subsequent ones.

See TCPOpenCommand documentation (neddoc) for more info.

Referenced by TCPSessionApp::activity().

{listen(false);}
void TCPSocket::processMessage ( cMessage *  msg)

Examines the message (which should have arrived from TCP), updates socket state, and if there is a callback object installed (see setCallbackObject(), class CallbackInterface), dispatches to the appropriate method of it with the same yourPtr that you gave in the setCallbackObject() call.

The method deletes the message, unless (1) there is a callback object installed AND (2) the message is payload (message kind TCP_I_DATA or TCP_I_URGENT_DATA) when the responsibility of destruction is on the socketDataArrived() callback method.

IMPORTANT: for performance reasons, this method doesn't check that the message belongs to this socket, i.e. belongsToSocket(msg) would return true!

Referenced by TCPSessionApp::activity(), TCPSrvHostApp::handleMessage(), TCPGenericCliAppBase::handleMessage(), LDP::processMessageFromTCP(), and TCPSessionApp::waitUntil().

{
    ASSERT(belongsToSocket(msg));

    TCPStatusInfo *status;
    TCPConnectInfo *connectInfo;
    switch (msg->getKind())
    {
        case TCP_I_DATA:
             if (cb)
                 cb->socketDataArrived(connId, yourPtr, PK(msg), false);
             else
                 delete msg;
             break;
        case TCP_I_URGENT_DATA:
             if (cb)
                 cb->socketDataArrived(connId, yourPtr, PK(msg), true);
             else
                 delete msg;
             break;
        case TCP_I_ESTABLISHED:
             // Note: this code is only for sockets doing active open, and nonforking
             // listening sockets. For a forking listening sockets, TCP_I_ESTABLISHED
             // carries a new connId which won't match the connId of this TCPSocket,
             // so you won't get here. Rather, when you see TCP_I_ESTABLISHED, you'll
             // want to create a new TCPSocket object via new TCPSocket(msg).
             sockstate = CONNECTED;
             connectInfo = dynamic_cast<TCPConnectInfo *>(msg->getControlInfo());
             localAddr = connectInfo->getLocalAddr();
             remoteAddr = connectInfo->getRemoteAddr();
             localPrt = connectInfo->getLocalPort();
             remotePrt = connectInfo->getRemotePort();
             delete msg;
             if (cb)
                 cb->socketEstablished(connId, yourPtr);
             break;
        case TCP_I_PEER_CLOSED:
             sockstate = sockstate==CONNECTED ? PEER_CLOSED : CLOSED;
             delete msg;
             if (cb)
                 cb->socketPeerClosed(connId, yourPtr);
             break;
        case TCP_I_CLOSED:
             sockstate = CLOSED;
             delete msg;
             if (cb)
                 cb->socketClosed(connId, yourPtr);
             break;
        case TCP_I_CONNECTION_REFUSED:
        case TCP_I_CONNECTION_RESET:
        case TCP_I_TIMED_OUT:
             sockstate = SOCKERROR;
             if (cb)
                 cb->socketFailure(connId, yourPtr, msg->getKind());
             delete msg;
             break;
        case TCP_I_STATUS:
             status = check_and_cast<TCPStatusInfo *>(msg->removeControlInfo());
             delete msg;
             if (cb)
                 cb->socketStatusArrived(connId, yourPtr, status);
             break;
        default:
             opp_error("TCPSocket: invalid msg kind %d, one of the TCP_I_xxx constants expected", msg->getKind());
    }
}
void TCPSocket::renewSocket ( )

Required to re-connect with a "used" TCPSocket object. By default, a TCPSocket object is tied to a single TCP connection, via the connectionId. When the connection gets closed or aborted, you cannot use the socket to connect again (by connect() or listen()) unless you obtain a new connectionId by calling this method.

BEWARE if you use TCPSocketMap! TCPSocketMap uses connectionId to find TCPSockets, so after calling this method you have to remove the socket from your TCPSocketMap, and re-add it. Otherwise TCPSocketMap will get confused.

The reason why one must obtain a new connectionId is that TCP still has to maintain the connection data structure (identified by the old connectionId) internally for a while (2 maximum segment lifetimes = 240s) after it reported "connection closed" to us.

Referenced by TCPGenericCliAppBase::connect().

{
    connId = ev.getUniqueNumber();
    remoteAddr = localAddr = IPvXAddress();
    remotePrt = localPrt = -1;

    sockstate = NOT_BOUND;
}
void TCPSocket::requestStatus ( )

Causes TCP to reply with a fresh TCPStatusInfo, attached to a dummy message as getControlInfo(). The reply message can be recognized by its message kind TCP_I_STATUS, or (if a callback object is used) the socketStatusArrived() method of the callback object will be called.

{
    cMessage *msg = new cMessage("STATUS", TCP_C_STATUS);
    TCPCommand *cmd = new TCPCommand();
    cmd->setConnId(connId);
    msg->setControlInfo(cmd);
    sendToTCP(msg);
}
void TCPSocket::send ( cMessage *  msg)

Sends data packet.

Referenced by TCPSessionApp::activity(), TCPGenericSrvThread::dataArrived(), TCPGenericCliAppBase::sendPacket(), LDP::sendToPeer(), and sendToTCP().

{
    if (sockstate!=CONNECTED && sockstate!=CONNECTING && sockstate!=PEER_CLOSED)
        opp_error("TCPSocket::send(): not connected or connecting");

    msg->setKind(TCP_C_SEND);
    TCPSendCommand *cmd = new TCPSendCommand();
    cmd->setConnId(connId);
    msg->setControlInfo(cmd);
    sendToTCP(msg);
}
void TCPSocket::sendToTCP ( cMessage *  msg) [protected]

Referenced by abort(), close(), connect(), listen(), requestStatus(), and send().

{
    if (!gateToTcp)
        opp_error("TCPSocket: setOutputGate() must be invoked before socket can be used");

    check_and_cast<cSimpleModule *>(gateToTcp->getOwnerModule())->send(msg, gateToTcp);
}
void TCPSocket::setCallbackObject ( CallbackInterface cb,
void *  yourPtr = NULL 
)

Sets a callback object, to be used with processMessage(). This callback object may be your simple module itself (if it multiply inherits from CallbackInterface too, that is you declared it as

 class MyAppModule : public cSimpleModule, public TCPSocket::CallbackInterface
 

and redefined the necessary virtual functions; or you may use dedicated class (and objects) for this purpose.

TCPSocket doesn't delete the callback object in the destructor or on any other occasion.

YourPtr is an optional pointer. It may contain any value you wish -- TCPSocket will not look at it or do anything with it except passing it back to you in the CallbackInterface calls. You may find it useful if you maintain additional per-connection information: in that case you don't have to look it up by connId in the callbacks, you can have it passed to you as yourPtr.

Referenced by TCPSrvHostApp::handleMessage(), TCPGenericCliAppBase::initialize(), and LDP::openTCPConnectionToPeer().

{
    cb = callback;
    yourPtr = yourPointer;
}
void TCPSocket::setOutputGate ( cGate *  toTcp) [inline]
void TCPSocket::setReceiveQueueClass ( const char *  receiveQueueClass) [inline]

Sets the receiveQueueClass parameter of the next connect() or listen() call.

void TCPSocket::setSendQueueClass ( const char *  sendQueueClass) [inline]

Sets the sendQueueClass parameter of the next connect() or listen() call.

void TCPSocket::setTCPAlgorithmClass ( const char *  tcpAlgorithmClass) [inline]

Sets the tcpAlgorithmClass parameter of the next connect() or listen() call.

const char * TCPSocket::stateName ( int  state) [static]

Returns name of socket state code returned by getState().

Referenced by operator<<().

{
#define CASE(x) case x: s=#x; break
    const char *s = "unknown";
    switch (state)
    {
        CASE(NOT_BOUND);
        CASE(BOUND);
        CASE(LISTENING);
        CASE(CONNECTING);
        CASE(CONNECTED);
        CASE(PEER_CLOSED);
        CASE(LOCALLY_CLOSED);
        CASE(CLOSED);
        CASE(SOCKERROR);
    }
    return s;
#undef CASE
}

Member Data Documentation

cGate* TCPSocket::gateToTcp [protected]

Referenced by sendToTCP(), and TCPSocket().

std::string TCPSocket::receiveQueueClass [protected]

Referenced by connect(), and listen().

std::string TCPSocket::sendQueueClass [protected]

Referenced by connect(), and listen().

std::string TCPSocket::tcpAlgorithmClass [protected]

Referenced by connect(), and listen().

void* TCPSocket::yourPtr [protected]

The documentation for this class was generated from the following files: