C12Adapter Opensource C++ Interface
MChannelSocket Class Reference

MChannelSocket implements the channel interface for an TCP/IP socket. More...

Inheritance diagram for MChannelSocket:

Public Member Functions

 MChannelSocket ()
 Construct the socket channel.
 
virtual ~MChannelSocket ()
 Destructor.
 
virtual void Connect ()
 Establishes connection to the device using a socket. More...
 
virtual void WaitForNextIncomingConnection (bool reinitialize=true)
 When GetAutoAnswer true, wait for the incoming connection without disconnecting the channel. More...
 
virtual void Disconnect ()
 Disconnect brings down the connection and releases the socket.
 
const MStreamSocketGetSocketConst () const
 Get the constant socket object that is used by this channel.
 
virtual void CheckIfConnected ()
 Throw an appropriate exception if the channel is not connected. More...
 
MStreamSocketGetSocket ()
 
virtual void SetSocket (MStreamSocketBase &)
 
const MStdStringGetProxyString () const
 
void SetProxyString (const MStdString &proxyString)
 
bool GetHandlePeerDisconnect () const
 
void SetHandlePeerDisconnect (bool yes)
 
unsigned GetConnectTimeout () const
 
void SetConnectTimeout (unsigned timeout)
 
- Public Member Functions inherited from MChannelSocketBase
virtual ~MChannelSocketBase ()
 Destructor.
 
virtual bool IsConnected () const
 Returns the current state of the socket channel.
 
const MStreamSocketBaseGetSocketConst () const
 Get the constant socket object that is used by this channel.
 
MStdString GetActualLocalAddress () const
 Get the actual address of the local socket as it is known by Sockets. More...
 
unsigned GetActualLocalPort () const
 Get the actual port number of the local socket as it is known by Sockets. More...
 
MStdString GetActualPeerAddress () const
 Get the actual address of the peer socket as it is known by Sockets. More...
 
unsigned GetActualPeerPort () const
 Get the actual port number of the peer socket as it is known by Sockets. More...
 
virtual void FlushOutputBuffer (unsigned numberOfCharsInBuffer=UINT_MAX)
 Ensure that the characters from the output buffer are sent. More...
 
virtual MStdString GetMediaIdentification () const
 Return a string that identifies the media through which this channel is talking. More...
 
unsigned GetAutoAnswerPort () const
 
void SetAutoAnswerPort (unsigned port)
 
const MStdStringGetAutoAnswerAddress () const
 
void SetAutoAnswerAddress (const MStdString &addr)
 
MStreamSocketBaseGetSocket ()
 
const MStdStringGetPeerAddress () const
 
void SetPeerAddress (const MStdString &addr)
 
unsigned GetPeerPort () const
 
void SetPeerPort (unsigned port)
 
- Public Member Functions inherited from MChannel
virtual MChannelCreateClone () const
 Virtual copy constructor, creates the channel, which is a clone of current. More...
 
virtual ~MChannel ()
 The destructor is public, and virtual. More...
 
void WriteBytes (const MByteString &buffer)
 Writes the data to the channel, and returns when the last byte has been sent by the software. More...
 
void WriteByte (Muint8 b)
 Writes a byte to the channel, and returns when it has been sent. More...
 
void WriteBuffer (const char *buf, unsigned len)
 Writes the data buffer to the channel, and returns when the last character has been sent by the software (but hardware might still need to do some work). More...
 
Muint8 ReadByte ()
 Read a single byte from the channel. More...
 
void ReadBuffer (char *buf, unsigned numberToRead)
 Read an exact number of characters from the channel. More...
 
void Unread (const MVariant &byteOrBytes)
 Return the given byte or bytes to the stream buffer so they get read at the next read operation. More...
 
void UnreadBuffer (const char *buff, unsigned size)
 Return the given bytes to the stream buffer so they get read at the next read operation. More...
 
MByteString ReadBytes (unsigned numberToRead)
 Read bytes directly from the communication channel. More...
 
MByteString ReadBytesUntil (const MByteString &terminatingString)
 Read bytes from the channel until a specified sequence is read. More...
 
MByteString ReadBytesUntilAnyByte (const char *finisher, unsigned finisherSize, unsigned headerSize, unsigned footerSize)
 Read bytes from the channel until a specified sequence is read. More...
 
MByteString ReadAllBytes ()
 Read an arbitrary number of characters from the channel, as much as available. More...
 
void ClearInputBuffer ()
 Immediately discards all the pending characters from the channel. More...
 
void ClearInputUntilSilence (unsigned milliseconds)
 Keep reading and ignoring input until there is silence. More...
 
void CheckIfConnectedConst () const
 Throw an appropriate exception if the channel is not connected, constant version. More...
 
unsigned GetCountBytesSent () const
 Number of bytes sent through the channel since its creation or since the last ResetCounts(). More...
 
unsigned GetCountBytesReceived () const
 The number of bytes received through the channel since creation or since the last ResetCounts(). More...
 
void ResetCounts ()
 Reset channel statistical data, so the counters become zeros. More...
 
virtual void WriteToMonitor (const MStdString &message)
 Synchronously write a message to the monitor, if it is connected. More...
 
virtual void CancelCommunication (bool callDisconnect=false)
 Request canceling of the communication. More...
 
void EnterUninterruptibleCommunication (bool notify=true)
 Enter a communication sequence that shall not be be interrupted with CancelCommunication call. More...
 
void LeaveUninterruptibleCommunication (bool notify=true)
 Leave a communication sequence that shall not be be interrupted with CancelCommunication call. More...
 
void CheckIfOperationIsCancelled ()
 Check if the user has requested the termination of the communication, and whether the cancel operation lock is zero. More...
 
void Sleep (unsigned milliseconds)
 Channel version of Sleep, a delay function that is aware of cancel communication event. More...
 
unsigned ReadWithTimeout (char *buf, unsigned size, unsigned timeout)
 Read up to size bytes into buffer using the given timeout. More...
 
bool GetAutoAnswer () const
 
void SetAutoAnswer (bool isAutoAnswer)
 
unsigned GetAutoAnswerTimeout () const
 
void SetAutoAnswerTimeout (unsigned timeout)
 
void SetMonitor (MMonitor::Pointer monitor)
 
MMonitor::Pointer GetMonitor () const
 
SHOW_INTERNAL bool GetEcho () const
 
void SetEcho (bool echo)
 
bool GetSendEchoBytesToMonitor () const
 
void SetSendEchoBytesToMonitor (bool doSend)
 
unsigned GetIntercharacterTimeout () const
 
void SetIntercharacterTimeout (unsigned timeout)
 
unsigned GetReadTimeout () const
 
void SetReadTimeout (unsigned timeout)
 
unsigned GetWriteTimeout () const
 
void SetWriteTimeout (unsigned timeout)
 
- Public Member Functions inherited from MCOMObject
virtual ~MCOMObject ()
 Object destructor.
 
virtual MStdStringVector GetAllPropertyNames () const
 Return the list of publicly available properties in MCOM syntax. More...
 
virtual MStdStringVector GetAllPersistentPropertyNames () const
 Return the list of publicly available persistent properties in MCOM syntax. More...
 
MStdString GetPersistentPropertyValues (bool onlyNondefaults=false, bool excludeSecurityRelated=false) const
 Get the string with the list of persistent property names and their values. More...
 
void SetPersistentPropertyValues (const MStdString &values)
 Set the persistent properties for the object using the string with the following format: More...
 
void SetPropertyValues (const MDictionary &values)
 Set the properties for the object using the property list object. More...
 
void WritePropertiesToMonitor ()
 Write all non-default values of protocol properties into monitor. More...
 
MStdString DoGetPersistentPropertyValues0 () const
 Get the string with the whole list of persistent property names and their values. More...
 
MStdString DoGetPersistentPropertyValues1 (bool onlyNondefaults) const
 Get the string with the list of persistent property names and their values. More...
 
- Public Member Functions inherited from MObject
virtual ~MObject ()
 Object destructor.
 
virtual const MClassGetClass () const =0
 Get the final class of the object. More...
 
virtual unsigned GetEmbeddedSizeof () const
 For embedded object types, return the size of the class. More...
 
bool IsEmbeddedObject () const
 Tell if the object is of embedded kind. More...
 
SHOW_INTERNAL MVariant Call (const MStdString &name, const MVariant &params)
 Call the object service with parameters, given as variant. More...
 
MVariant Call0 (const MStdString &name)
 Call the object service with no parameters. More...
 
MVariant Call1 (const MStdString &name, const MVariant &p1)
 Call the object service with one parameter. More...
 
MVariant Call2 (const MStdString &name, const MVariant &p1, const MVariant &p2)
 Call the object service with two parameter. More...
 
MVariant Call3 (const MStdString &name, const MVariant &p1, const MVariant &p2, const MVariant &p3)
 Call the object service with three parameter. More...
 
MVariant Call4 (const MStdString &name, const MVariant &p1, const MVariant &p2, const MVariant &p3, const MVariant &p4)
 Call the object service with four parameter. More...
 
MVariant Call5 (const MStdString &name, const MVariant &p1, const MVariant &p2, const MVariant &p3, const MVariant &p4, const MVariant &p5)
 Call the object service with five parameter. More...
 
MVariant Call6 (const MStdString &name, const MVariant &p1, const MVariant &p2, const MVariant &p3, const MVariant &p4, const MVariant &p5, const MVariant &p6)
 Call the object service with six parameter. More...
 
virtual MVariant CallV (const MStdString &name, const MVariant::VariantVector &params)
 Call the object service with parameters, given as variant vector. More...
 
virtual bool IsPropertyPresent (const MStdString &name) const
 Tell if the property with the given name exists.
 
virtual bool IsServicePresent (const MStdString &name) const
 Tell if the service with the given name exists.
 
virtual MVariant GetProperty (const MStdString &name) const
 Get the property value using name of the property. More...
 
virtual void SetProperty (const MStdString &name, const MVariant &value)
 Set the property using name of the property, and value. More...
 
virtual void SetPersistentPropertiesToDefault ()
 Set the persistent properties of the object to their default values. More...
 
virtual MVariant GetPersistentPropertyDefaultValue (const MStdString &name) const
 Get the default value of persistent property with the name given. More...
 
virtual void SetPersistentPropertyToDefault (const MStdString &name)
 Set the persistent property with the name given to default value. More...
 
virtual const char * GetType () const
 Get the name of the type for the object (could be the same as class name).
 
virtual void SetType (const MStdString &)
 Intentionally, it will set the name of the type for the object, but the service will not allow setting the name to anything other than the current name. More...
 
virtual void Validate ()
 Validate internal structures of the object. More...
 

Additional Inherited Members

- Public Types inherited from MChannel
enum  { CANCEL_COMMUNICATION_CHECK_OPTIMUM_INTERVAL = 1000 }
 
- Static Public Member Functions inherited from MObject
static const MClassGetStaticClass ()
 Get the declared class of this particular object. More...
 
static bool IsClassPresent (const MStdString &name)
 Tells if the given class name is available. More...
 
- Static Public Attributes inherited from MObject
static const MClass s_class
 Class of MObject.
 
- Protected Member Functions inherited from MChannelSocketBase
 MChannelSocketBase ()
 Construct the abstract socket channel.
 
- Protected Member Functions inherited from MChannel
 MChannel ()
 Construct the channel object from parent class. More...
 
- Protected Member Functions inherited from MCOMObject
 MCOMObject ()
 Object constructor, protected as the class is abstract.
 
- Protected Member Functions inherited from MObject
 MObject ()
 Object constructor, protected as the class is abstract.
 
void DoSetPersistentPropertiesToDefault (const MClass *staticClass)
 Set the persistent properties to their default values for one object provided the class for that object. More...
 

Detailed Description

MChannelSocket implements the channel interface for an TCP/IP socket.

MChannelSocket implements TCP/IP socket behavior over channel socket base. Socket connections can be made to the peer device (outbound) or from the peer device (inbound). Either connection direction can be made with MChannelSocket or MMChannelSocketCallback. The default property values for MChannelSocket are tuned for an outbound connection, and the default property values for MChannelSocketCallback are tuned for an inbound connection. The connection attempt can take a long time to complete or time out. If the connection is queued with QConnect and committed asynchronously with QCommit(True), then the connection can be aborted with QAbort.

Member Function Documentation

virtual void MChannelSocket::CheckIfConnected ( )
virtual

Throw an appropriate exception if the channel is not connected.

The exception can be different depending on whether the connection was not made previously, or if the connection was unexpectedly terminated.

Precondition
The channel is connected, or an exception is thrown.
See also
CheckIfConnectedConst - constant version of this method

Reimplemented from MChannel.

virtual void MChannelSocket::Connect ( )
virtual

Establishes connection to the device using a socket.

The property GetConnectTimeout, when nonzero, can alter the duration defined by the operating system for a connection to be established.

Precondition
IsConnected should be false before calling this method. Many OS and program exceptions can be thrown by this method.

Implements MChannelSocketBase.

unsigned MChannelSocket::GetConnectTimeout ( ) const
inline

Timeout in seconds for TCP/IP connection to be established.

A connection timeout will only result from socket errors such as when the connected party did not respond after a certain period of time. Any other socket connect errors, such as Destination host is unreachable, are reported immediately.

If this property is zero, the operating system defined connect timeout is in effect, which can vary from 10 to 180 seconds or more, depending on the internal TCP/IP settings, and the networking devices involved.

If the property is nonzero, the operating system behavior is altered, and a new timeout takes effect.

When ConnectTimeout expires before the operating system timeout, the error thrown is MCOMException, code 0x8004180E, with text (in case of English locale): "Failed to connect within X seconds" where X is the value of this property. Small connect timeouts are useful on private networks where the connection time to an online device is fast.

When ConnectTimeout expires after the operating system timeout, the connection is attempted in a loop until it is established, or fails. If it fails, the error thrown is MESocketError with text from the last operating system error. Very large connect timeouts can be used to wait for a device to come online. Due to limits in the operating system timer utilized by MeteringSDK, values larger than MAX_INT/1000 (which is about 24 days), is considered to be an eternity, and the timeout is disabled (it will wait forever). Care should be taken when using large values, especially with synchronous communications, as one could lock up an application. Applications that allow the user to specify the ConnectTimeout, may wish to limit the maximum value.

At any moment, the user can cancel the ongoing Connect() call by issuing CancelCommunication(), in which case MEOperationCancelled is raised.

Possible values:
  • 0 Operating system defined TCP/IP connection timeout is in effect.
  • 1 .. MAX_INT/1000 - 1 Connect timeout in seconds takes effect for cases when the host is not responding.
  • MAX_INT/1000 .. MAX_UINT Try to connect forever until succeeding or failing with a socket error, which is not a timeout.
Default value:
0 means the connect time is limited only by the OS behavior.
bool MChannelSocket::GetHandlePeerDisconnect ( ) const
inline

Determines whether or not to immediately close the socket when the peer has closed (sent message with FIN flag).

When true, this property helps work around the issue where the peer device locks up because it did not receive a response to its FIN message in a timely manner. This can happen when the application is busy with its own processing and does not read from the socket for an extended period of time. By the time the application does send the ACK, it is too late as the wireless link has already died. When FIN is detected, the ACK is sent back, and then the socket is immediately closed by sending FIN to the peer. This prevents the connection from remaining in FIN_WAIT_1 or FIN_WAIT_2 (half-closed) state for a long time, leading to known problems in certain devices.

Note that many socket channels can have different values of HandlePeerDisconnect in the same process. There is only one thread that polls the open sockets and it only monitors those that have HandlePeerDisconnect = true. This design helps minimize the impact to performance, but it adds extra synchronization, which can lead to extended delays in socket handling when there are many monitored sockets (hundreds or thousands).

Since
MeteringSDK Version 5.4.0.2427.
Possible values:
  • True - the open socket is periodically polled in order to handle the incoming FIN message in a timely manner.
  • False - the socket is not polled. This is also the behavior of builds prior to 5.4.0.2400.
Default value:
True
const MStdString& MChannelSocket::GetProxyString ( ) const
inline

SOCKS5 proxy configuration string.

This is a combination of proxy server address, network port number (optional), and authorization string (optional), divided with colons. Authorization string is a username or username and password divided by '@'. Proxy server address is either the IP address as string, or a DNS name.

Examples:

  • 10.20.30.40 (uses default port 1080)
  • example.com (uses default port 1080)
  • example.com:4050
  • username:example.com:1080 (with authorization by username)
  • username@password:example.com:1080 (with authorization by username and password)
Since
MeteringSDK Version 5.0.0.890.
Default value:
"" (empty string)
MStreamSocket& MChannelSocket::GetSocket ( )
inline

Socket object that is used by this channel.

Setting socket has a feature: what actually happens, this channel's socket is swapped with the given socket. MChannelSocket accepts only MStreamSocket object as input.

void MChannelSocket::SetConnectTimeout ( unsigned  timeout)
inline

Timeout in seconds for TCP/IP connection to be established.

A connection timeout will only result from socket errors such as when the connected party did not respond after a certain period of time. Any other socket connect errors, such as Destination host is unreachable, are reported immediately.

If this property is zero, the operating system defined connect timeout is in effect, which can vary from 10 to 180 seconds or more, depending on the internal TCP/IP settings, and the networking devices involved.

If the property is nonzero, the operating system behavior is altered, and a new timeout takes effect.

When ConnectTimeout expires before the operating system timeout, the error thrown is MCOMException, code 0x8004180E, with text (in case of English locale): "Failed to connect within X seconds" where X is the value of this property. Small connect timeouts are useful on private networks where the connection time to an online device is fast.

When ConnectTimeout expires after the operating system timeout, the connection is attempted in a loop until it is established, or fails. If it fails, the error thrown is MESocketError with text from the last operating system error. Very large connect timeouts can be used to wait for a device to come online. Due to limits in the operating system timer utilized by MeteringSDK, values larger than MAX_INT/1000 (which is about 24 days), is considered to be an eternity, and the timeout is disabled (it will wait forever). Care should be taken when using large values, especially with synchronous communications, as one could lock up an application. Applications that allow the user to specify the ConnectTimeout, may wish to limit the maximum value.

At any moment, the user can cancel the ongoing Connect() call by issuing CancelCommunication(), in which case MEOperationCancelled is raised.

Possible values:
  • 0 Operating system defined TCP/IP connection timeout is in effect.
  • 1 .. MAX_INT/1000 - 1 Connect timeout in seconds takes effect for cases when the host is not responding.
  • MAX_INT/1000 .. MAX_UINT Try to connect forever until succeeding or failing with a socket error, which is not a timeout.
Default value:
0 means the connect time is limited only by the OS behavior.
void MChannelSocket::SetHandlePeerDisconnect ( bool  yes)

Determines whether or not to immediately close the socket when the peer has closed (sent message with FIN flag).

When true, this property helps work around the issue where the peer device locks up because it did not receive a response to its FIN message in a timely manner. This can happen when the application is busy with its own processing and does not read from the socket for an extended period of time. By the time the application does send the ACK, it is too late as the wireless link has already died. When FIN is detected, the ACK is sent back, and then the socket is immediately closed by sending FIN to the peer. This prevents the connection from remaining in FIN_WAIT_1 or FIN_WAIT_2 (half-closed) state for a long time, leading to known problems in certain devices.

Note that many socket channels can have different values of HandlePeerDisconnect in the same process. There is only one thread that polls the open sockets and it only monitors those that have HandlePeerDisconnect = true. This design helps minimize the impact to performance, but it adds extra synchronization, which can lead to extended delays in socket handling when there are many monitored sockets (hundreds or thousands).

Since
MeteringSDK Version 5.4.0.2427.
Possible values:
  • True - the open socket is periodically polled in order to handle the incoming FIN message in a timely manner.
  • False - the socket is not polled. This is also the behavior of builds prior to 5.4.0.2400.
Default value:
True
void MChannelSocket::SetProxyString ( const MStdString proxyString)
inline

SOCKS5 proxy configuration string.

This is a combination of proxy server address, network port number (optional), and authorization string (optional), divided with colons. Authorization string is a username or username and password divided by '@'. Proxy server address is either the IP address as string, or a DNS name.

Examples:

  • 10.20.30.40 (uses default port 1080)
  • example.com (uses default port 1080)
  • example.com:4050
  • username:example.com:1080 (with authorization by username)
  • username@password:example.com:1080 (with authorization by username and password)
Since
MeteringSDK Version 5.0.0.890.
Default value:
"" (empty string)
virtual void MChannelSocket::SetSocket ( MStreamSocketBase )
virtual

Socket object that is used by this channel.

Setting socket has a feature: what actually happens, this channel's socket is swapped with the given socket. MChannelSocket accepts only MStreamSocket object as input.

Implements MChannelSocketBase.

virtual void MChannelSocket::WaitForNextIncomingConnection ( bool  reinitialize = true)
virtual

When GetAutoAnswer true, wait for the incoming connection without disconnecting the channel.

A typical server application sequence that uses this call:

Connect() // wait for the first incoming connection
loop until interrupted:
... communicate ...
WaitForNextIncomingConnection() // wait for the next incoming connection
end loop
Parameters
reinitializeTells if reinitialization of the channel has to be made at each new incoming connection.
Precondition
Prior to this call, the channel needs to be configured with SetAutoAnswer true, and the connection established with Connect(). Not all channels support Auto Answer mode, and might throw an exception. A timeout exception is thrown if no call is received during the GetAutoAnswerTimeout period.

Reimplemented from MChannel.