INET Framework for OMNeT++/OMNEST
|
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 |
CallbackInterface * | cb |
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... | |
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);
Enumerator | |
---|---|
NOT_BOUND | |
BOUND | |
LISTENING | |
CONNECTING | |
CONNECTED | |
PEER_CLOSED | |
LOCALLY_CLOSED | |
CLOSED | |
SOCKERROR |
inet::TCPSocket::TCPSocket | ( | ) |
Constructor.
The getConnectionId() method returns a valid Id right after constructor call.
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.
inet::TCPSocket::~TCPSocket | ( | ) |
Destructor.
void inet::TCPSocket::abort | ( | ) |
Aborts the connection.
Referenced by inet::bgp::BGPRouting::openTCPConnectionToPeer(), and inet::NetPerfMeter::teardownConnection().
|
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().)
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().
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().
void inet::TCPSocket::bind | ( | L3Address | localAddr, |
int | localPort | ||
) |
Bind the socket to a local port number and IP address (useful with multi-homing).
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().
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().
|
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().
|
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().
|
inline |
Returns the current dataTransferMode parameter.
Referenced by inet::TCPSessionApp::createDataPacket().
|
inline |
Referenced by inet::bgp::BGPSession::sendOpenMessage().
|
inline |
|
inline |
Referenced by inet::bgp::BGPRouting::processMessageFromTCP(), and inet::LDP::processMessageFromTCP().
|
inline |
|
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 inet::TelnetApp::handleOperationStage(), inet::TCPBasicClientApp::handleOperationStage(), inet::TCPSessionApp::handleOperationStage(), inet::bgp::BGPRouting::openTCPConnectionToPeer(), inet::operator<<(), inet::TCPSinkApp::refreshDisplay(), inet::TCPAppBase::refreshDisplay(), inet::TCPSessionApp::refreshDisplay(), inet::TCPBasicClientApp::socketDataArrived(), inet::httptools::HttpServer::socketPeerClosed(), inet::TCPAppBase::socketPeerClosed(), and inet::httptools::HttpBrowser::socketPeerClosed().
|
inline |
Returns the current tcpAlgorithmClass parameter.
|
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().
|
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().
|
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.
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().
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().
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().
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.
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().
void inet::TCPSocket::sendCommand | ( | cMessage * | msg | ) |
|
protected |
Referenced by abort(), close(), connect(), listen(), requestStatus(), send(), and sendCommand().
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().
|
inline |
Sets the dataTransferMode parameter of the subsequent connect() or listen() calls.
Referenced by inet::httptools::HttpServer::handleMessage(), inet::httptools::HttpServer::initialize(), inet::TCPGenericSrvApp::initialize(), and inet::httptools::HttpBrowser::submitToSocket().
|
inline |
Sets the gate on which to send to TCP.
Must be invoked before socket can be used. Example: socket.setOutputGate(gate("tcpOut"));
Referenced by inet::NetPerfMeter::createAndBindSocket(), inet::TCPSrvHostApp::handleMessage(), inet::httptools::HttpServer::handleMessage(), inet::TCPSinkApp::initialize(), inet::TCPSrvHostApp::initialize(), inet::httptools::HttpServer::initialize(), inet::TCPAppBase::initialize(), inet::TCPGenericSrvApp::initialize(), inet::TCPEchoApp::initialize(), inet::LDP::initialize(), inet::bgp::BGPRouting::openTCPConnectionToPeer(), inet::LDP::openTCPConnectionToPeer(), inet::bgp::BGPRouting::processMessageFromTCP(), inet::LDP::processMessageFromTCP(), inet::httptools::HttpBrowser::submitToSocket(), and inet::NetPerfMeter::successfullyEstablishedConnection().
|
inline |
|
inline |
|
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().
|
protected |
Referenced by processMessage(), setCallbackObject(), TCPSocket(), and ~TCPSocket().
|
protected |
Referenced by abort(), belongsToSocket(), close(), connect(), listen(), processMessage(), renewSocket(), requestStatus(), send(), TCPSocket(), and ~TCPSocket().
|
protected |
Referenced by connect(), listen(), readDataTransferModePar(), and TCPSocket().
|
protected |
Referenced by sendToTCP(), and TCPSocket().
|
protected |
Referenced by bind(), connect(), listen(), processMessage(), renewSocket(), and TCPSocket().
|
protected |
Referenced by bind(), connect(), listen(), processMessage(), renewSocket(), and TCPSocket().
|
protected |
Referenced by connect(), processMessage(), renewSocket(), and TCPSocket().
|
protected |
Referenced by connect(), processMessage(), renewSocket(), and TCPSocket().
|
protected |
Referenced by abort(), bind(), close(), connect(), listen(), processMessage(), renewSocket(), send(), and TCPSocket().
|
protected |
Referenced by processMessage(), setCallbackObject(), TCPSocket(), and ~TCPSocket().