INET Framework for OMNeT++/OMNEST
inet::TCPSocket Class Reference

TCPSocket is a convenience class, to make it easier to manage TCP connections from your application models. More...

#include <TCPSocket.h>

Classes

class  CallbackInterface
 Abstract base class for your callback objects. More...
 

Public Types

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

Public Member Functions

 TCPSocket ()
 Constructor. More...
 
 TCPSocket (cMessage *msg)
 Constructor, to be used with forked sockets (see listen()). More...
 
 ~TCPSocket ()
 Destructor. More...
 
int getConnectionId () const
 Returns the internal connection Id. More...
 
int getState () const
 Returns the socket state, one of NOT_BOUND, CLOSED, LISTENING, CONNECTING, CONNECTED, etc. More...
 
void setState (enum State state)
 
Getter functions
L3Address getLocalAddress ()
 
int getLocalPort ()
 
L3Address getRemoteAddress ()
 
int getRemotePort ()
 

Static Public Member Functions

static const char * stateName (int state)
 Returns name of socket state code returned by getState(). More...
 

Protected Member Functions

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

Protected Attributes

int connId
 
int sockstate
 
L3Address localAddr
 
int localPrt
 
L3Address remoteAddr
 
int remotePrt
 
CallbackInterfacecb
 
void * yourPtr
 
cGate * gateToTcp
 
TCPDataTransferMode dataTransferMode
 
std::string tcpAlgorithmClass
 

Opening and closing connections, sending data

void setOutputGate (cGate *toTcp)
 Sets the gate on which to send to TCP. More...
 
void bind (int localPort)
 Bind the socket to a local port number. More...
 
void bind (L3Address localAddr, int localPort)
 Bind the socket to a local port number and IP address (useful with multi-homing). More...
 
TCPDataTransferMode getDataTransferMode () const
 Returns the current dataTransferMode parameter. More...
 
const char * getTCPAlgorithmClass () const
 Returns the current tcpAlgorithmClass parameter. More...
 
void setDataTransferMode (TCPDataTransferMode transferMode)
 Sets the dataTransferMode parameter of the subsequent connect() or listen() calls. More...
 
void readDataTransferModePar (cComponent &component)
 Read "dataTransferMode" parameter from ini/ned, and set dataTransferMode member value. More...
 
void setTCPAlgorithmClass (const char *tcpAlgorithmClass)
 Sets the tcpAlgorithmClass parameter of the next connect() or listen() call. More...
 
void listen ()
 Initiates passive OPEN, creating a "forking" connection that will listen on the port you bound the socket to. More...
 
void listenOnce ()
 Initiates passive OPEN to create a non-forking listening connection. More...
 
void connect (L3Address remoteAddr, int remotePort)
 Active OPEN to the given remote socket. More...
 
void send (cMessage *msg)
 Sends data packet. More...
 
void sendCommand (cMessage *msg)
 Sends command. More...
 
void close ()
 Closes the local end of the connection. More...
 
void abort ()
 Aborts the connection. More...
 
void requestStatus ()
 Causes TCP to reply with a fresh TCPStatusInfo, attached to a dummy message as getControlInfo(). More...
 
void renewSocket ()
 Required to re-connect with a "used" TCPSocket object. More...
 
static TCPDataTransferMode convertStringToDataTransferMode (const char *transferMode)
 Convert a string to TCPDataTransferMode enum. More...
 

Handling of messages arriving from TCP

bool 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.) More...
 
void setCallbackObject (CallbackInterface *cb, void *yourPtr=nullptr)
 Sets a callback object, to be used with processMessage(). More...
 
void 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. More...
 
static bool belongsToAnyTCPSocket (cMessage *msg)
 Returns true if the message belongs to any TCPSocket instance. More...
 

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(Address("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,nullptr);
}
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, nullptr);
    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 
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148

Constructor & Destructor Documentation

inet::TCPSocket::TCPSocket ( )

Constructor.

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

23 {
24  // don't allow user-specified connIds because they may conflict with
25  // automatically assigned ones.
26  connId = getEnvir()->getUniqueNumber();
28 
29  localPrt = remotePrt = -1;
30  cb = nullptr;
31  yourPtr = nullptr;
32 
33  gateToTcp = nullptr;
35 }
int connId
Definition: TCPSocket.h:151
int localPrt
Definition: TCPSocket.h:155
int sockstate
Definition: TCPSocket.h:152
Definition: TCPSocket.h:148
void * yourPtr
Definition: TCPSocket.h:160
CallbackInterface * cb
Definition: TCPSocket.h:159
TCPDataTransferMode dataTransferMode
Definition: TCPSocket.h:164
Definition: TCPCommand_m.h:254
cGate * gateToTcp
Definition: TCPSocket.h:162
int remotePrt
Definition: TCPSocket.h:157
inet::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.

38 {
39  TCPCommand *ind = dynamic_cast<TCPCommand *>(msg->getControlInfo());
40 
41  if (!ind)
42  throw cRuntimeError("TCPSocket::TCPSocket(cMessage *): no TCPCommand control info in message (not from TCP?)");
43 
44  connId = ind->getConnId();
46 
47  localPrt = remotePrt = -1;
48  cb = nullptr;
49  yourPtr = nullptr;
50  dataTransferMode = TCP_TRANSFER_UNDEFINED; // FIXME set dataTransferMode
51  gateToTcp = nullptr;
52 
53  if (msg->getKind() == TCP_I_ESTABLISHED) {
54  // management of stockstate is left to processMessage() so we always
55  // set it to CONNECTED in the ctor, whatever TCP_I_xxx arrives.
56  // However, for convenience we extract TCPConnectInfo already here, so that
57  // remote address/port can be read already after the ctor call.
58 
59  TCPConnectInfo *connectInfo = check_and_cast<TCPConnectInfo *>(msg->getControlInfo());
60  localAddr = connectInfo->getLocalAddr();
61  remoteAddr = connectInfo->getRemoteAddr();
62  localPrt = connectInfo->getLocalPort();
63  remotePrt = connectInfo->getRemotePort();
64  }
65 }
int connId
Definition: TCPSocket.h:151
Definition: TCPCommand_m.h:100
Definition: TCPSocket.h:148
int localPrt
Definition: TCPSocket.h:155
int sockstate
Definition: TCPSocket.h:152
void * yourPtr
Definition: TCPSocket.h:160
L3Address remoteAddr
Definition: TCPSocket.h:156
CallbackInterface * cb
Definition: TCPSocket.h:159
TCPDataTransferMode dataTransferMode
Definition: TCPSocket.h:164
Definition: TCPCommand_m.h:254
cGate * gateToTcp
Definition: TCPSocket.h:162
L3Address localAddr
Definition: TCPSocket.h:154
int remotePrt
Definition: TCPSocket.h:157
inet::TCPSocket::~TCPSocket ( )

Destructor.

68 {
69  if (cb)
71 }
int connId
Definition: TCPSocket.h:151
void * yourPtr
Definition: TCPSocket.h:160
CallbackInterface * cb
Definition: TCPSocket.h:159
virtual void socketDeleted(int connId, void *yourPtr)
Definition: TCPSocket.h:145

Member Function Documentation

void inet::TCPSocket::abort ( )

Aborts the connection.

Referenced by inet::bgp::BGPRouting::openTCPConnectionToPeer(), and inet::NetPerfMeter::teardownConnection().

206 {
208  cMessage *msg = new cMessage("ABORT", TCP_C_ABORT);
209  TCPCommand *cmd = new TCPCommand();
210  cmd->setConnId(connId);
211  msg->setControlInfo(cmd);
212  sendToTCP(msg);
213  }
214  sockstate = CLOSED;
215 }
int connId
Definition: TCPSocket.h:151
void sendToTCP(cMessage *msg)
Definition: TCPSocket.cc:93
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
int sockstate
Definition: TCPSocket.h:152
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
Definition: TCPCommand_m.h:65
bool inet::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().)

241 {
242  return dynamic_cast<TCPCommand *>(msg->getControlInfo());
243 }
bool inet::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().

235 {
236  return dynamic_cast<TCPCommand *>(msg->getControlInfo()) &&
237  ((TCPCommand *)(msg->getControlInfo()))->getConnId() == connId;
238 }
int connId
Definition: TCPSocket.h:151
void inet::TCPSocket::bind ( int  localPort)

Bind the socket to a local port number.

Referenced by inet::NetPerfMeter::createAndBindSocket(), inet::TCPSinkApp::initialize(), inet::TCPSrvHostApp::initialize(), inet::httptools::HttpServer::initialize(), inet::TCPAppBase::initialize(), inet::TCPGenericSrvApp::initialize(), inet::LDP::initialize(), inet::bgp::BGPRouting::openTCPConnectionToPeer(), inet::LDP::openTCPConnectionToPeer(), and inet::TCPEchoApp::startListening().

102 {
103  if (sockstate != NOT_BOUND)
104  throw cRuntimeError("TCPSocket::bind(): socket already bound");
105 
106  if (lPort < 0 || lPort > 65535)
107  throw cRuntimeError("TCPSocket::bind(): invalid port number %d", lPort);
108 
109  localPrt = lPort;
110  sockstate = BOUND;
111 }
int localPrt
Definition: TCPSocket.h:155
int sockstate
Definition: TCPSocket.h:152
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
void inet::TCPSocket::bind ( L3Address  localAddr,
int  localPort 
)

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

114 {
115  if (sockstate != NOT_BOUND)
116  throw cRuntimeError("TCPSocket::bind(): socket already bound");
117 
118  // allow -1 here, to make it possible to specify address only
119  if ((lPort < 0 || lPort > 65535) && lPort != -1)
120  throw cRuntimeError("TCPSocket::bind(): invalid port number %d", lPort);
121 
122  localAddr = lAddr;
123  localPrt = lPort;
124  sockstate = BOUND;
125 }
int localPrt
Definition: TCPSocket.h:155
int sockstate
Definition: TCPSocket.h:152
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
L3Address localAddr
Definition: TCPSocket.h:154
void inet::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 inet::TCPAppBase::close(), inet::TCPGenericSrvThread::dataArrived(), inet::NetPerfMeter::handleTimer(), inet::bgp::BGPRouting::processMessageFromTCP(), inet::httptools::HttpBrowser::socketDataArrived(), inet::httptools::HttpBrowser::socketEstablished(), inet::httptools::HttpServer::socketPeerClosed(), inet::httptools::HttpBrowser::socketPeerClosed(), and inet::TCPEchoApp::stopListening().

193 {
195  throw cRuntimeError("TCPSocket::close(): not connected or close() already called (sockstate=%s)", stateName(sockstate));
196 
197  cMessage *msg = new cMessage("CLOSE", TCP_C_CLOSE);
198  TCPCommand *cmd = new TCPCommand();
199  cmd->setConnId(connId);
200  msg->setControlInfo(cmd);
201  sendToTCP(msg);
203 }
Definition: TCPSocket.h:148
int connId
Definition: TCPSocket.h:151
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
void sendToTCP(cMessage *msg)
Definition: TCPSocket.cc:93
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
static const char * stateName(int state)
Returns name of socket state code returned by getState().
Definition: TCPSocket.cc:73
Definition: TCPSocket.h:148
int sockstate
Definition: TCPSocket.h:152
Definition: TCPCommand_m.h:64
void inet::TCPSocket::connect ( L3Address  remoteAddr,
int  remotePort 
)

Active OPEN to the given remote socket.

Referenced by inet::TCPAppBase::connect(), inet::NetPerfMeter::establishConnection(), inet::bgp::BGPRouting::openTCPConnectionToPeer(), inet::LDP::openTCPConnectionToPeer(), and inet::httptools::HttpBrowser::submitToSocket().

149 {
150  if (sockstate != NOT_BOUND && sockstate != BOUND)
151  throw cRuntimeError("TCPSocket::connect(): connect() or listen() already called (need renewSocket()?)");
152 
153  if (remotePort < 0 || remotePort > 65535)
154  throw cRuntimeError("TCPSocket::connect(): invalid remote port number %d", remotePort);
155 
156  cMessage *msg = new cMessage("ActiveOPEN", TCP_C_OPEN_ACTIVE);
157 
158  remoteAddr = remoteAddress;
159  remotePrt = remotePort;
160 
161  TCPOpenCommand *openCmd = new TCPOpenCommand();
162  openCmd->setConnId(connId);
163  openCmd->setLocalAddr(localAddr);
164  openCmd->setLocalPort(localPrt);
165  openCmd->setRemoteAddr(remoteAddr);
166  openCmd->setRemotePort(remotePrt);
167  openCmd->setDataTransferMode(dataTransferMode);
168  openCmd->setTcpAlgorithmClass(tcpAlgorithmClass.c_str());
169 
170  msg->setControlInfo(openCmd);
171  sendToTCP(msg);
173 }
Definition: TCPCommand_m.h:61
int connId
Definition: TCPSocket.h:151
std::string tcpAlgorithmClass
Definition: TCPSocket.h:165
Definition: TCPSocket.h:148
void sendToTCP(cMessage *msg)
Definition: TCPSocket.cc:93
int localPrt
Definition: TCPSocket.h:155
int sockstate
Definition: TCPSocket.h:152
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
L3Address remoteAddr
Definition: TCPSocket.h:156
TCPDataTransferMode dataTransferMode
Definition: TCPSocket.h:164
L3Address localAddr
Definition: TCPSocket.h:154
int remotePrt
Definition: TCPSocket.h:157
TCPDataTransferMode inet::TCPSocket::convertStringToDataTransferMode ( const char *  transferMode)
static

Convert a string to TCPDataTransferMode enum.

Returns TCP_TRANSFER_UNDEFINED when string has an invalid value Generate runtime error, when string is nullptr;

Referenced by readDataTransferModePar().

339 {
340  if (nullptr == transferMode || 0 == transferMode[0])
341  return TCP_TRANSFER_UNDEFINED;
342 
343  if (0 == strcmp(transferMode, "bytecount"))
344  return TCP_TRANSFER_BYTECOUNT;
345 
346  if (0 == strcmp(transferMode, "object"))
347  return TCP_TRANSFER_OBJECT;
348 
349  if (0 == strcmp(transferMode, "bytestream"))
351 
352  return TCP_TRANSFER_UNDEFINED;
353 }
Definition: TCPCommand_m.h:255
Definition: TCPCommand_m.h:257
Definition: TCPCommand_m.h:256
Definition: TCPCommand_m.h:254
int inet::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 inet::TCPSocketMap::addSocket(), inet::bgp::BGPRouting::findIdFromSocketConnId(), inet::TCPSocketMap::removeSocket(), and inet::httptools::HttpBrowser::socketDeleted().

197 { return connId; }
int connId
Definition: TCPSocket.h:151
TCPDataTransferMode inet::TCPSocket::getDataTransferMode ( ) const
inline

Returns the current dataTransferMode parameter.

See also
TCPCommand

Referenced by inet::TCPSessionApp::createDataPacket().

245 { return dataTransferMode; }
TCPDataTransferMode dataTransferMode
Definition: TCPSocket.h:164
L3Address inet::TCPSocket::getLocalAddress ( )
inline

Referenced by inet::bgp::BGPSession::sendOpenMessage().

215 { return localAddr; }
L3Address localAddr
Definition: TCPSocket.h:154
int inet::TCPSocket::getLocalPort ( )
inline
216 { return localPrt; }
int localPrt
Definition: TCPSocket.h:155
L3Address inet::TCPSocket::getRemoteAddress ( )
inline

Referenced by inet::bgp::BGPRouting::processMessageFromTCP(), and inet::LDP::processMessageFromTCP().

217 { return remoteAddr; }
L3Address remoteAddr
Definition: TCPSocket.h:156
int inet::TCPSocket::getRemotePort ( )
inline
218 { return remotePrt; }
int remotePrt
Definition: TCPSocket.h:157
const char* inet::TCPSocket::getTCPAlgorithmClass ( ) const
inline

Returns the current tcpAlgorithmClass parameter.

250 { return tcpAlgorithmClass.c_str(); }
std::string tcpAlgorithmClass
Definition: TCPSocket.h:165
void inet::TCPSocket::listen ( bool  fork)
protected

Referenced by inet::NetPerfMeter::createAndBindSocket(), inet::TCPSinkApp::initialize(), inet::TCPSrvHostApp::initialize(), inet::httptools::HttpServer::initialize(), inet::TCPGenericSrvApp::initialize(), inet::LDP::initialize(), and inet::TCPEchoApp::startListening().

128 {
129  if (sockstate != BOUND)
130  throw cRuntimeError(sockstate == NOT_BOUND ? "TCPSocket: must call bind() before listen()"
131  : "TCPSocket::listen(): connect() or listen() already called");
132 
133  cMessage *msg = new cMessage("PassiveOPEN", TCP_C_OPEN_PASSIVE);
134 
135  TCPOpenCommand *openCmd = new TCPOpenCommand();
136  openCmd->setLocalAddr(localAddr);
137  openCmd->setLocalPort(localPrt);
138  openCmd->setConnId(connId);
139  openCmd->setFork(fork);
140  openCmd->setDataTransferMode(dataTransferMode);
141  openCmd->setTcpAlgorithmClass(tcpAlgorithmClass.c_str());
142 
143  msg->setControlInfo(openCmd);
144  sendToTCP(msg);
146 }
Definition: TCPSocket.h:148
int connId
Definition: TCPSocket.h:151
std::string tcpAlgorithmClass
Definition: TCPSocket.h:165
void sendToTCP(cMessage *msg)
Definition: TCPSocket.cc:93
int localPrt
Definition: TCPSocket.h:155
int sockstate
Definition: TCPSocket.h:152
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
Definition: TCPCommand_m.h:62
TCPDataTransferMode dataTransferMode
Definition: TCPSocket.h:164
L3Address localAddr
Definition: TCPSocket.h:154
void inet::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().

289 { listen(true); }
void listen()
Initiates passive OPEN, creating a "forking" connection that will listen on the port you bound the so...
Definition: TCPSocket.h:289
void inet::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.

298 { listen(false); }
void listen()
Initiates passive OPEN, creating a "forking" connection that will listen on the port you bound the so...
Definition: TCPSocket.h:289
void inet::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 inet::TCPSrvHostApp::handleMessage(), inet::httptools::HttpServer::handleMessage(), inet::TCPAppBase::handleMessage(), inet::httptools::HttpBrowser::handleMessage(), inet::bgp::BGPRouting::processMessageFromTCP(), and inet::LDP::processMessageFromTCP().

252 {
253  ASSERT(belongsToSocket(msg));
254 
255  TCPStatusInfo *status;
256  TCPConnectInfo *connectInfo;
257 
258  switch (msg->getKind()) {
259  case TCP_I_DATA:
260  if (cb)
261  cb->socketDataArrived(connId, yourPtr, PK(msg), false);
262  else
263  delete msg;
264 
265  break;
266 
267  case TCP_I_URGENT_DATA:
268  if (cb)
269  cb->socketDataArrived(connId, yourPtr, PK(msg), true);
270  else
271  delete msg;
272 
273  break;
274 
275  case TCP_I_ESTABLISHED:
276  // Note: this code is only for sockets doing active open, and nonforking
277  // listening sockets. For a forking listening sockets, TCP_I_ESTABLISHED
278  // carries a new connId which won't match the connId of this TCPSocket,
279  // so you won't get here. Rather, when you see TCP_I_ESTABLISHED, you'll
280  // want to create a new TCPSocket object via new TCPSocket(msg).
282  connectInfo = check_and_cast<TCPConnectInfo *>(msg->getControlInfo());
283  localAddr = connectInfo->getLocalAddr();
284  remoteAddr = connectInfo->getRemoteAddr();
285  localPrt = connectInfo->getLocalPort();
286  remotePrt = connectInfo->getRemotePort();
287  delete msg;
288 
289  if (cb)
291 
292  break;
293 
294  case TCP_I_PEER_CLOSED:
296  delete msg;
297 
298  if (cb)
300 
301  break;
302 
303  case TCP_I_CLOSED:
304  sockstate = CLOSED;
305  delete msg;
306 
307  if (cb)
309 
310  break;
311 
314  case TCP_I_TIMED_OUT:
316 
317  if (cb)
318  cb->socketFailure(connId, yourPtr, msg->getKind());
319 
320  delete msg;
321  break;
322 
323  case TCP_I_STATUS:
324  status = check_and_cast<TCPStatusInfo *>(msg->removeControlInfo());
325  delete msg;
326 
327  if (cb)
329 
330  break;
331 
332  default:
333  throw cRuntimeError("TCPSocket: invalid msg kind %d, one of the TCP_I_xxx constants expected",
334  msg->getKind());
335  }
336 }
virtual void socketClosed(int connId, void *yourPtr)
Definition: TCPSocket.h:142
Definition: TCPCommand_m.h:102
int connId
Definition: TCPSocket.h:151
Definition: TCPCommand_m.h:101
virtual void socketFailure(int connId, void *yourPtr, int code)
Definition: TCPSocket.h:143
Definition: TCPCommand_m.h:100
Definition: TCPSocket.h:148
Definition: TCPCommand_m.h:104
Definition: TCPCommand_m.h:99
virtual void socketEstablished(int connId, void *yourPtr)
Definition: TCPSocket.h:140
Definition: TCPSocket.h:148
bool belongsToSocket(cMessage *msg)
Returns true if the message belongs to this socket instance (message has a TCPCommand as getControlIn...
Definition: TCPSocket.cc:234
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
virtual void socketPeerClosed(int connId, void *yourPtr)
Definition: TCPSocket.h:141
int localPrt
Definition: TCPSocket.h:155
int sockstate
Definition: TCPSocket.h:152
void * yourPtr
Definition: TCPSocket.h:160
virtual void socketDataArrived(int connId, void *yourPtr, cPacket *msg, bool urgent)=0
virtual void socketStatusArrived(int connId, void *yourPtr, TCPStatusInfo *status)
Definition: TCPSocket.h:144
L3Address remoteAddr
Definition: TCPSocket.h:156
#define PK(msg)
Definition: INETDefs.h:92
CallbackInterface * cb
Definition: TCPSocket.h:159
Definition: TCPCommand_m.h:106
Definition: TCPCommand_m.h:98
L3Address localAddr
Definition: TCPSocket.h:154
Definition: TCPCommand_m.h:103
Definition: TCPCommand_m.h:105
int remotePrt
Definition: TCPSocket.h:157
void inet::TCPSocket::readDataTransferModePar ( cComponent &  component)

Read "dataTransferMode" parameter from ini/ned, and set dataTransferMode member value.

Generate runtime error when parameter is missing or value is invalid.

Referenced by inet::NetPerfMeter::createAndBindSocket(), inet::TCPSinkApp::initialize(), inet::TCPSrvHostApp::initialize(), inet::TCPAppBase::initialize(), inet::TCPEchoApp::initialize(), inet::TCPSessionApp::initialize(), inet::LDP::initialize(), inet::bgp::BGPRouting::openTCPConnectionToPeer(), inet::LDP::openTCPConnectionToPeer(), inet::bgp::BGPRouting::processMessageFromTCP(), inet::LDP::processMessageFromTCP(), and inet::NetPerfMeter::successfullyEstablishedConnection().

356 {
357  const char *transferMode = component.par("dataTransferMode");
358 
359  if (nullptr == transferMode)
360  throw cRuntimeError("Missing dataTransferMode parameter at %s.",
361  component.getFullPath().c_str());
362 
364 
365  if (x == TCP_TRANSFER_UNDEFINED)
366  throw cRuntimeError("Invalid '%s' dataTransferMode parameter at %s.",
367  transferMode, component.getFullPath().c_str());
368 
369  dataTransferMode = x;
370 }
static TCPDataTransferMode convertStringToDataTransferMode(const char *transferMode)
Convert a string to TCPDataTransferMode enum.
Definition: TCPSocket.cc:338
TCPDataTransferMode
Enum generated from inet/transportlayer/contract/tcp/TCPCommand.msg:120 by nedtool.
Definition: TCPCommand_m.h:253
TCPDataTransferMode dataTransferMode
Definition: TCPSocket.h:164
Definition: TCPCommand_m.h:254
void inet::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 inet::TCPAppBase::connect(), inet::NetPerfMeter::establishConnection(), inet::bgp::BGPRouting::openTCPConnectionToPeer(), and inet::TCPEchoApp::startListening().

227 {
228  connId = getEnvir()->getUniqueNumber();
229  remoteAddr = localAddr = L3Address();
230  remotePrt = localPrt = -1;
232 }
int connId
Definition: TCPSocket.h:151
int localPrt
Definition: TCPSocket.h:155
int sockstate
Definition: TCPSocket.h:152
Definition: TCPSocket.h:148
L3Address remoteAddr
Definition: TCPSocket.h:156
L3Address localAddr
Definition: TCPSocket.h:154
int remotePrt
Definition: TCPSocket.h:157
void inet::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.

218 {
219  cMessage *msg = new cMessage("STATUS", TCP_C_STATUS);
220  TCPCommand *cmd = new TCPCommand();
221  cmd->setConnId(connId);
222  msg->setControlInfo(cmd);
223  sendToTCP(msg);
224 }
int connId
Definition: TCPSocket.h:151
void sendToTCP(cMessage *msg)
Definition: TCPSocket.cc:93
Definition: TCPCommand_m.h:66
void inet::TCPSocket::send ( cMessage *  msg)

Sends data packet.

Referenced by inet::TCPGenericSrvThread::dataArrived(), inet::bgp::BGPSession::sendKeepAliveMessage(), inet::bgp::BGPSession::sendOpenMessage(), inet::TCPAppBase::sendPacket(), inet::LDP::sendToPeer(), sendToTCP(), inet::httptools::HttpServer::socketDataArrived(), inet::httptools::HttpBrowser::socketEstablished(), and inet::NetPerfMeter::transmitFrame().

176 {
178  throw cRuntimeError("TCPSocket::send(): socket not connected or connecting, state is %s", stateName(sockstate));
179 
180  msg->setKind(TCP_C_SEND);
181  TCPSendCommand *cmd = new TCPSendCommand();
182  cmd->setConnId(connId);
183  msg->setControlInfo(cmd);
184  sendToTCP(msg);
185 }
int connId
Definition: TCPSocket.h:151
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
void sendToTCP(cMessage *msg)
Definition: TCPSocket.cc:93
Definition: TCPCommand_m.h:63
Definition: TCPSocket.h:148
static const char * stateName(int state)
Returns name of socket state code returned by getState().
Definition: TCPSocket.cc:73
int sockstate
Definition: TCPSocket.h:152
void inet::TCPSocket::sendCommand ( cMessage *  msg)

Sends command.

Referenced by inet::NetPerfMeter::sendTCPQueueRequest().

188 {
189  sendToTCP(msg);
190 }
void sendToTCP(cMessage *msg)
Definition: TCPSocket.cc:93
void inet::TCPSocket::sendToTCP ( cMessage *  msg)
protected

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

94 {
95  if (!gateToTcp)
96  throw cRuntimeError("TCPSocket: setOutputGate() must be invoked before socket can be used");
97 
98  check_and_cast<cSimpleModule *>(gateToTcp->getOwnerModule())->send(msg, gateToTcp);
99 }
void send(cMessage *msg)
Sends data packet.
Definition: TCPSocket.cc:175
cGate * gateToTcp
Definition: TCPSocket.h:162
void inet::TCPSocket::setCallbackObject ( CallbackInterface cb,
void *  yourPtr = nullptr 
)

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 inet::TCPSrvHostApp::handleMessage(), inet::httptools::HttpServer::handleMessage(), inet::httptools::HttpServer::initialize(), inet::TCPAppBase::initialize(), inet::bgp::BGPRouting::openTCPConnectionToPeer(), inet::LDP::openTCPConnectionToPeer(), inet::bgp::BGPRouting::processMessageFromTCP(), and inet::httptools::HttpBrowser::submitToSocket().

246 {
247  cb = callback;
248  yourPtr = yourPointer;
249 }
void * yourPtr
Definition: TCPSocket.h:160
CallbackInterface * cb
Definition: TCPSocket.h:159
void inet::TCPSocket::setDataTransferMode ( TCPDataTransferMode  transferMode)
inline

Sets the dataTransferMode parameter of the subsequent connect() or listen() calls.

See also
TCPCommand

Referenced by inet::httptools::HttpServer::handleMessage(), inet::httptools::HttpServer::initialize(), inet::TCPGenericSrvApp::initialize(), and inet::httptools::HttpBrowser::submitToSocket().

263 { dataTransferMode = transferMode; }
TCPDataTransferMode dataTransferMode
Definition: TCPSocket.h:164
void inet::TCPSocket::setState ( enum State  state)
inline
211 { sockstate = state; };
int sockstate
Definition: TCPSocket.h:152
void inet::TCPSocket::setTCPAlgorithmClass ( const char *  tcpAlgorithmClass)
inline

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

std::string tcpAlgorithmClass
Definition: TCPSocket.h:165
const char * inet::TCPSocket::stateName ( int  state)
static

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

Referenced by close(), inet::operator<<(), inet::TCPSinkApp::refreshDisplay(), inet::TCPAppBase::refreshDisplay(), inet::TCPSessionApp::refreshDisplay(), and send().

74 {
75 #define CASE(x) case x: \
76  s = #x; break
77  const char *s = "unknown";
78  switch (state) {
79  CASE(NOT_BOUND);
80  CASE(BOUND);
81  CASE(LISTENING);
83  CASE(CONNECTED);
86  CASE(CLOSED);
87  CASE(SOCKERROR);
88  }
89  return s;
90 #undef CASE
91 }
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
Definition: TCPSocket.h:148
#define CASE(x)
value< double, units::s > s
Definition: Units.h:1049

Member Data Documentation

CallbackInterface* inet::TCPSocket::cb
protected
TCPDataTransferMode inet::TCPSocket::dataTransferMode
protected
cGate* inet::TCPSocket::gateToTcp
protected

Referenced by sendToTCP(), and TCPSocket().

L3Address inet::TCPSocket::localAddr
protected
int inet::TCPSocket::localPrt
protected
L3Address inet::TCPSocket::remoteAddr
protected
int inet::TCPSocket::remotePrt
protected
int inet::TCPSocket::sockstate
protected
std::string inet::TCPSocket::tcpAlgorithmClass
protected

Referenced by connect(), and listen().

void* inet::TCPSocket::yourPtr
protected

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