Cross-Platform C++

ot::net
class Socket

#include "ot/net/Socket.h"

ot::ManagedObject Provides a Berkeley socket interface for TCP/IP stream sockets. A TCP/IP socket is an end-point for reliable communication between two networked machines.

The Socket class manages a socket handle which is provided by the underlying operating system. This handle is represented by a SocketDescriptor, which enables OpenTop to close the socket handle when it is no longer required.

When a Socket is created, it can be connected to a specific end-point by using an appropriate constructor, or it can be connected after construction using one of the connect() methods.

Data is sent over the Socket connection using an OutputStream returned from getOutputStream() and received using an InputStream returned from getInputStream().

The actual work of the Socket is performed by an instance of the SocketImpl class. Instances of SocketImpl are created using a factory class: SocketImplFactory. An application can change the socket factory that creates the socket implementation by calling SetSocketImplFactory() on this class. The default socket factory creates plain SocketImpl instances which do not perform any special processing.

Multi-threaded considerations:
Static functions are synchronized for safe access from multiple concurrent threads but instance member functions are not. A Socket may be shared between multiple threads if the application provides adequate synchronization. For example, it is acceptable for one thread to read from a socket while another thread writes to the same socket, but if two threads wish to read from the same socket they will have to synchronize their access to the InputStream.



Constructor/Destructor Summary
Socket()
         Creates an unconnected socket.
Socket(SocketImpl* pImpl)
         Protected constructor that creates a Socket using the passed SocketImpl.
Socket(InetAddress* pAddress, int port)
         Creates a Socket and connects it to the specified port on the network host designated by the provided InetAddress.
Socket(const String& host, int port)
         Creates a Socket that is connected to a specified host name and port.
Socket(InetAddress* pAddress, int port, InetAddress* pLocalAddr, int localPort)
         Creates a Socket and connects it to the specified remote port on the network host designated by the provided InetAddress.
Socket(const String& host, int port, InetAddress* pLocalAddr, int localPort)
        

Method Summary
 virtual void close()
         Closes the Socket and releases any system resources associated with it.
 virtual void connect(InetAddress* pAddress, int port)
         Connects an unconnected socket to a port on a remote host.
 virtual void connect(const String& host, int port)
         Connects an unconnected socket to a port on a remote host.
 virtual void connect(InetAddress* pAddress, int port, size_t timeoutMS)
         Connects an unconnected socket to a port on a remote host.
 virtual bool getAutoClose() const
         Tests if auto_close is enabled.
 virtual RefPtr< InetAddress > getInetAddress() const
         Returns an InetAddress representing the remote host to which this Socket is connected.
 virtual RefPtr< InputStream > getInputStream() const
         Returns an InputStream that can be used to read data from this Socket.
 virtual bool getKeepAlive() const
         Tests if SO_KEEPALIVE is enabled.
 virtual RefPtr< InetAddress > getLocalAddress() const
         Returns an InetAddress representing the local address to which this Socket is bound.
 virtual int getLocalPort() const
         Returns the local port number to which this socket is bound.
 virtual RefPtr< OutputStream > getOutputStream() const
         Returns an OutputStream that can be used to write data to this Socket.
 virtual int getPort() const
         Returns the remote port to which this socket is connected.
 virtual int getReceiveBufferSize() const
         Returns the SO_RVCBUF option for this Socket, which is the size of the buffer used by the operating system to hold received data before it is read by the application.
 virtual int getSendBufferSize() const
         Returns the value of the SO_SNDBUF option for this Socket, which is the size of the buffer used by the operating system to store output data from the application before it is sent to (and acknowledged by) the connected host.
static RefPtr< SocketImplFactory > GetSocketImplFactory()
         Returns the static object that is the SocketImplFactory for client sockets.
 virtual int getSoLinger() const
         Returns the setting for the SO_LINGER option for this Socket.
 virtual size_t getSoTimeout() const
         Returns the value of the SO_TIMEOUT pseudo option.
 virtual bool getTcpNoDelay() const
         Tests if the TCP_NODELAY option is enabled for this Socket.
 virtual bool isClosed()
         Tests if this socket is closed.
 virtual bool isConnected()
         Tests the connected status of this Socket.
 virtual void setAutoClose(bool bEnable)
         Enables/disables the auto_close feature.
 virtual void setKeepAlive(bool bEnable)
         Enables/disables the SO_KEEPALIVE option for this Socket.
 virtual void setReceiveBufferSize(size_t size)
         Sets the SO_RCVBUF option for this Socket, which is the size of the buffer used by the operating system to hold received data before it is read by the application.
 virtual void setSendBufferSize(size_t size)
         Sets the SO_SNDBUF option for this Socket, which is the size of the buffer used by the operating system to store output data from the application before it is sent to (and acknowledged by) the connected host.
static void SetSocketImplFactory(SocketImplFactory* pFac)
         Sets the client socket implementation factory for the application.
 virtual void setSoLinger(bool bEnable, size_t linger)
         Sets the SO_LINGER option for this Socket.
 virtual void setSoTimeout(size_t timeoutMS)
         Enables/disables the SO_TIMEOUT pseudo option.
 virtual void setTcpNoDelay(bool bEnable)
         Enables/disables the TCP_NODELAY option for this Socket.
 virtual void shutdownInput()
         Shuts down this Socket for input operations.
 virtual void shutdownOutput()
         Shuts down this Socket for output operations.
 virtual String toString() const
         Returns a string representation of this Socket.

Methods inherited from class ot::ManagedObject
addRef, getRefCount, onFinalRelease, operator=, release

Constructor/Destructor Detail

Socket

 Socket()
Creates an unconnected socket. The registered socket factory is used to create an instance of SocketImpl to perform the actual work for the socket.

Before the socket can be used to communicate with an end-point, it must first be connected using connect().

Exceptions:
SocketException - if an error occurs creating the socket.

Socket

protected  Socket(SocketImpl* pImpl)
Protected constructor that creates a Socket using the passed SocketImpl.

Exceptions:
NullPointerException - if pSocketImpl is null.

Socket

 Socket(InetAddress* pAddress,
        int port)
Creates a Socket and connects it to the specified port on the network host designated by the provided InetAddress. The registered socket factory is used to create an instance of SocketImpl to perform the actual work for the socket.

Exceptions:
SocketException - if an error occurs creating or connecting the socket.
NullPointerException - if pAddress is null.
See also:
connect()

Socket

 Socket(const String& host,
        int port)
Creates a Socket that is connected to a specified host name and port. The host name is first resolved into an InetAddress before connecting to it.

Parameters:
host - the name of the remote host or a string representation of its IP-address in the form "xxx.xxx.xxx.xxx".
Exceptions:
UnknownHostException - if host cannot be resolved into an Internet address.
SocketException - if an error occurs creating or connecting the socket.
See also:
connect()

Socket

 Socket(InetAddress* pAddress,
        int port,
        InetAddress* pLocalAddr,
        int localPort)
Creates a Socket and connects it to the specified remote port on the network host designated by the provided InetAddress. The created Socket is bound to the specified local port and InetAddress.

If pLocalAddr is null, the socket is bound to any interface on the local host. If localPort is 0, the operating system chooses an unused local port number.

Exceptions:
NullPointerException - if pAddress is null.
SocketException - if an error occurs creating, binding or connecting the socket.
See also:
connect() , bind()

Socket

 Socket(const String& host,
        int port,
        InetAddress* pLocalAddr,
        int localPort)


Method Detail

close

virtual void close()
Closes the Socket and releases any system resources associated with it. This forces the underlying socket handle to be closed, even if the reference count of the contained SocketDescriptor indicates that it is being shared by other objects such as an InputStream or OutputStream.

Generally, applications will not need to call this function because the socket is automatically closed when the reference-count of the SocketDescriptor is decremented to zero.

Subsequent read or write operations will fail with an IOException except when using buffered streams, which may not register that the socket has been closed until the next time the buffer is refreshed or flushed.

Exceptions:
SocketException - if an error occurs closing the socket.

connect

virtual void connect(InetAddress* pAddress,
                     int port)
Connects an unconnected socket to a port on a remote host.

Parameters:
pAddress - an InetAddress representing the remote host
port - the port number on the remote host
Exceptions:
NullPointerException - if pAddress is null.
SocketException - if an error occurs connecting to the remote host.

connect

virtual void connect(const String& host,
                     int port)
Connects an unconnected socket to a port on a remote host.

Parameters:
host - the name of the remote host or a string representation of its IP-address in the form "xxx.xxx.xxx.xxx".
port - the port number on the remote host
Exceptions:
UnknownHostException - if host cannot be resolved into an Internet address.
SocketException - if an error occurs connecting to the remote host.

connect

virtual void connect(InetAddress* pAddress,
                     int port,
                     size_t timeoutMS)
Connects an unconnected socket to a port on a remote host. This overloaded method takes a timeout value which is used to specify (in milliseconds) the maximum time that the connection attempt should last before being aborted.

Parameters:
pAddress - an InetAddress representing the remote host
port - the port number on the remote host
timeoutMS - a time-out value in milliseconds
Exceptions:
NullPointerException - if pAddress is null.
SocketException - if an error occurs connecting to the remote host.
SocketTimeoutException - if timeoutMS milliseconds elapses before the connection is successfully established.

getAutoClose

virtual bool getAutoClose() const
Tests if auto_close is enabled.

Returns:
true if auto_close is enabled; false otherwise.
See also:
setAutoClose()

getInetAddress

virtual RefPtr< InetAddressgetInetAddress() const
Returns an InetAddress representing the remote host to which this Socket is connected. If this socket has never been connected a null RefPtr is returned.

Returns:
the remote InetAddress or null.
See also:
getLocalAddress()

getInputStream

virtual RefPtr< InputStreamgetInputStream() const
Returns an InputStream that can be used to read data from this Socket. Multiple calls to getInputStream() are guaranteed to always return the same object.

See also:
getOutputStream()

getKeepAlive

virtual bool getKeepAlive() const
Tests if SO_KEEPALIVE is enabled.

Returns:
true if SO_KEEPALIVE is enabled; false otherwise.
Exceptions:
SocketException - if an error occurs while interrogating the socket.
See also:
setKeepAlive()

getLocalAddress

virtual RefPtr< InetAddressgetLocalAddress() const
Returns an InetAddress representing the local address to which this Socket is bound. If this socket has never been bound a null RefPtr is returned.

Returns:
the local InetAddress or null if the socket has not been bound.
See also:
bind() , getInetAddress()

getLocalPort

virtual int getLocalPort() const
Returns the local port number to which this socket is bound.

Returns:
the local port number of -1 if this Socket is not yet connected.

getOutputStream

virtual RefPtr< OutputStreamgetOutputStream() const
Returns an OutputStream that can be used to write data to this Socket. Multiple calls to getOutputStream() are guaranteed to always return the same object.

See also:
getInputStream()

getPort

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

Returns:
the remote port number of -1 if this Socket is not yet connected.

getReceiveBufferSize

virtual int getReceiveBufferSize() const
Returns the SO_RVCBUF option for this Socket, which is the size of the buffer used by the operating system to hold received data before it is read by the application.

Returns:
the value of the SO_RCVBUF option for this Socket
Exceptions:
SocketException - if an error occurs while interrogating the socket.
See also:
setReceiveBufferSize()

getSendBufferSize

virtual int getSendBufferSize() const
Returns the value of the SO_SNDBUF option for this Socket, which is the size of the buffer used by the operating system to store output data from the application before it is sent to (and acknowledged by) the connected host.

Exceptions:
SocketException - if an error occurs while interrogating the socket.

GetSocketImplFactory

static RefPtr< SocketImplFactoryGetSocketImplFactory()
Returns the static object that is the SocketImplFactory for client sockets. An instance of the default SocketImplFactory is created if a factory has not already been registered by the application.


getSoLinger

virtual int getSoLinger() const
Returns the setting for the SO_LINGER option for this Socket.

Returns:
the value of the SO_LINGER option. A return value of -1 indicates that SO_LINGER is disabled for this Socket.
Exceptions:
SocketException - if an error occurs while interrogating the socket.

getSoTimeout

virtual size_t getSoTimeout() const
Returns the value of the SO_TIMEOUT pseudo option. SO_TIMEOUT is not one of the options defined for Berkeley sockets, but was actually introduced as part of the Java API. For client sockets it has the same meaning as the SO_RCVTIMEO option, which specifies the maximum number of milliseconds that a blocking read() call will wait for data to arrive on the socket.


getTcpNoDelay

virtual bool getTcpNoDelay() const
Tests if the TCP_NODELAY option is enabled for this Socket. When set, the TCP_NODELAY option disables Nagles algorithm, which is enabled by default.

Returns:
true if TCP_NODELAY is enabled; false otherwise.
Exceptions:
SocketException - if an error occurs while interrogating the socket.

isClosed

virtual bool isClosed()
Tests if this socket is closed.

Returns:
true if the Socket is closed; false otherwise.
Since:
1.3

isConnected

virtual bool isConnected()
Tests the connected status of this Socket.

Returns:
true if the Socket is connected; false otherwise.

setAutoClose

virtual void setAutoClose(bool bEnable)
Enables/disables the auto_close feature. The OpenTop auto_close facility is used to close a socket automatically when no OutputStream is referenced for the socket and an EndOfFile marker is read from the socket's InputStream. This feature may be useful for classes which return an InputStream and require the user to close the stream when OndOfFile is reached.

Parameters:
bEnable - if true the option is enabled; otherwise it is disabled.
Exceptions:
SocketException - if an error occurs while setting the auto_close option.
See also:
getAutoClose()

setKeepAlive

virtual void setKeepAlive(bool bEnable)
Enables/disables the SO_KEEPALIVE option for this Socket. When set, the SO_KEEPALIVE option causes the operating system to send a heartbeat packet at regular intervals when no other data is being sent over the socket.

Note that the time interval between heartbeat packets is controlled by the operating system, and may be as long as 2 hours.

Parameters:
bEnable - if true the option is enabled; otherwise it is disabled.
Exceptions:
SocketException - if an error occurs while setting the SO_KEEPALIVE option.
See also:
getKeepAlive()

setReceiveBufferSize

virtual void setReceiveBufferSize(size_t size)
Sets the SO_RCVBUF option for this Socket, which is the size of the buffer used by the operating system to hold received data before it is read by the application.

The SO_RCVBUF option can only be set before a client socket is connected to a remote host (buffer sizes are negotiated between hosts when the connection is established). A SocketException will be thrown if this method is called on a connected client Socket.

Parameters:
size - the requested buffer size (in bytes)
Exceptions:
SocketException - if an error occurs while setting the SO_RCVBUF option
See also:
isConnected() , getReceiveBufferSize()

setSendBufferSize

virtual void setSendBufferSize(size_t size)
Sets the SO_SNDBUF option for this Socket, which is the size of the buffer used by the operating system to store output data from the application before it is sent to (and acknowledged by) the connected host.

The SO_SNDBUF option can only be set before a client socket is connected to a remote host (buffer sizes are negotiated between hosts when the connection is established). A SocketException will be thrown if this method is called on a connected client Socket.

Parameters:
size - the requested buffer size (in bytes)
Exceptions:
SocketException - if an error occurs while setting the SO_SNDBUF option
See also:
isConnected() , getReceiveBufferSize()

SetSocketImplFactory

static void SetSocketImplFactory(SocketImplFactory* pFac)
Sets the client socket implementation factory for the application. When an application creates a new Socket, the registered socket implementation factory's createSocketImpl() method is called to create the actual SocketImpl instance which performs the work for the Socket.

An application should only call this function if it wishes to employ a customized SocketImpl class.

To ensure that the passed object exists for as long as the application needs it, the SocketImplFactory object is registered with the system's ObjectManager which holds a (counted) reference to it until system termination. This absolves the application from having to manage the lifetime of the passed object. For example, the following code is perfectly valid and does not cause a memory leak:-

   int main(int argc, char* argv[])
   {
      SystemMonitor _monitor();   // ensures clean termination
      // register a customized socket implementation factory
      Socket::SetSocketImplFactory(new MySocketImplFactory);
      ...
   }

Parameters:
pFac - a pointer to a SocketImplFactory
Exceptions:
NullPointerException - if pFac is null.
Multi-threaded considerations:
Can safely be called from multiple concurrent threads.

setSoLinger

virtual void setSoLinger(bool bEnable,
                         size_t linger)
Sets the SO_LINGER option for this Socket.

The SO_LINGER option specifies how the close() function operates. By default, close() returns immediately, but if there is any data still remaining in the socket's send buffer, the operating system will attempt to deliver that data to the connected host.

When the SO_LINGER option is enabled, calls to close() will wait for up to a specified length of time until that data has been sent and acknowledged.

Parameters:
bEnable - true to enable the SO_LINGER option, false to disable it.
linger - the desired time-out (in seconds).
Exceptions:
SocketException - if an error occurs while setting the SO_LINGER option.

setSoTimeout

virtual void setSoTimeout(size_t timeoutMS)
Enables/disables the SO_TIMEOUT pseudo option. SO_TIMEOUT is not one of the options defined for Berkeley sockets, but was actually introduced as part of the Java API. For client sockets it has the same meaning as the SO_RCVTIMEO option, which specifies the maximum number of milliseconds that a blocking read() call will wait for data to arrive on the socket.

Parameters:
timeoutMS - the specified timeout value, in milliseconds. A value of zero indicates no timeout, i.e. an infinite wait.

setTcpNoDelay

virtual void setTcpNoDelay(bool bEnable)
Enables/disables the TCP_NODELAY option for this Socket. When set, the TCP_NODELAY option disables Nagles algorithm, which is enabled by default.

Parameters:
bEnable - if true the option is enabled; otherwise it is disabled.
Exceptions:
SocketException - if an error occurs while setting the TCP_NODELAY option.

shutdownInput

virtual void shutdownInput()
Shuts down this Socket for input operations. Any unread data in the socket's receive buffer is discarded. Any read operations from this socket's InputStream will result in an EndOfFile condition.

Exceptions:
SocketException - if an error occurs shutting down the socket

shutdownOutput

virtual void shutdownOutput()
Shuts down this Socket for output operations. Any previously written data will be flushed to the peer host, followed by TCP's normal connection termination sequence. If an attempt is made to write data to the socket's output stream after invoking shutdownOutput(), an IOException will be thrown.

Exceptions:
SocketException - if an error occurs shutting down the socket

toString

virtual String toString() const
Returns a string representation of this Socket. The format of the returned string is dependent on the associated SocketImpl instance, but plain sockets return a string in the form:- Socket[addr=host/1.2.3.4,port=n,localport=n]



Cross-Platform C++

Found a bug or missing feature? Please email us at support@elcel.com

Copyright © 2000-2003 ElCel Technology   Trademark Acknowledgements