Aria  2.8.0
ArSocket Class Reference

socket communication wrapper More...

#include <ArSocket.h>

Public Types

enum  Error {
  NoErr, NetFail, ConBadHost, ConNoRoute,
  ConRefused, NameLookup
}
 
enum  Type { UDP, TCP, Unknown }
 

Public Member Functions

bool accept (ArSocket *sock)
 Accept a new connection. More...
 
 ArSocket ()
 Constructor. You must then use either connect() or open().
 
 ArSocket (const char *host, int port, Type type)
 Constructor which immediately connects to a server as a client host Hostname or IP address of remote server port Port number on server Which IP protocol to use, type ArSocket::TCP or ArSocket::UDP. More...
 
 ArSocket (int port, bool doClose, Type type)
 Constructor which immediately opens a port as a server port Port number to open. More...
 
void clearPartialReadString (void)
 Clears the partial string read.
 
bool close ()
 Close the socket. More...
 
int comparePartialReadString (const char *partialString)
 Compares a string against what was partially read.
 
bool connect (const char *host, int port, Type type=TCP, const char *openOnIP=NULL)
 Connect as a client to a server. More...
 
bool connectTo (const char *host, int port)
 Connect the socket to the given address. More...
 
bool connectTo (struct sockaddr_in *sin)
 Connect the socket to the given address. More...
 
bool copy (int fd, bool doclose)
 Copy internal socket structures. More...
 
void copy (ArSocket *s)
 Copy socket.
 
bool create (Type type)
 Simply create a port. More...
 
bool findValidPort (int startPort, const char *openOnIP=NULL)
 Find the first valid unused port after startPort, and bind the socket to it. More...
 
bool getBadRead (void) const
 Gets if we've had a bad read (you have to use error tracking for this)
 
bool getBadWrite (void) const
 Gets if we've had a bad write (you have to use error tracking for this)
 
long getBytesRecvd (void)
 Gets the number of bytes we've read.
 
long getBytesSent (void)
 Gets the number of bytes we've written.
 
ArFunctorgetCloseCallback (void)
 Sets the callback for when the socket is closed (nicely or harshly)
 
bool getEcho (void)
 Gets if we are echoing on the readString calls this socket does.
 
Error getError () const
 Get a code representing the last error.
 
const std::string & getErrorStr () const
 Get a string containing a description of the last error. Only valid if getError() does not return NoErr.
 
bool getErrorTracking (void)
 Gets whether we're doing error tracking or not.
 
int getFD () const
 Get the file descriptor.
 
const char * getIPString (void) const
 Gets the ip number as a string (this can be modified though)
 
ArTime getLastStringReadTime (void)
 Gets the time we last successfully read a string from the socket.
 
bool getLogWriteStrings (void)
 Gets whether we log the writeStrings or not.
 
const char * getRawIPString (void) const
 Gets the raw ip number as a string.
 
long getRecvs (void)
 Gets the number of reads we've done.
 
long getSends (void)
 Gets the number of writes we've done.
 
bool getSockName ()
 Get socket information (socket "name"). Aspects of this "name" are accessible with sockAddrIn(), inAddr(), inPort() More...
 
bool getStringUseWrongEndChars (void)
 Gets whether we log the writeStrings or not.
 
Type getType () const
 Get the protocol type.
 
struct in_addr * inAddr ()
 Accessor for the in_addr part of sockaddr.
 
unsigned short int inPort ()
 Accessor for the port of the sockaddr.
 
bool isOpen ()
 
bool open (int port, Type type, const char *openOnIP=NULL)
 Open a server port. More...
 
int read (void *buff, size_t len, unsigned int msWait=0)
 Read data from the socket. More...
 
char * readString (unsigned int msWait=0)
 Reads a string from the socket. More...
 
int recvFrom (void *msg, int len, sockaddr_in *sin)
 Receive a message (short string) from the socket. More...
 
void resetTracking (void)
 Resets the tracking information on the socket.
 
int sendTo (const void *msg, int len)
 Send a message (short string) on the socket. More...
 
int sendTo (const void *msg, int len, struct sockaddr_in *sin)
 Send a message (short string) on the socket. More...
 
bool setBroadcast ()
 Set broadcast value. More...
 
void setCloseCallback (ArFunctor *functor)
 Sets the callback for when the socket is closed (nicely or harshly)
 
void setDoClose (bool yesno)
 Change the doClose value.
 
void setEcho (bool echo)
 Sets echoing on the readString calls this socket does.
 
void setErrorTracking (bool errorTracking)
 Sets whether we're error tracking or not.
 
void setIPString (const char *ipString)
 Sets the ip string.
 
bool setLinger (int time)
 Set the linger value. More...
 
void setLogWriteStrings (bool logWriteStrings)
 Sets whether we log the writeStrings or not.
 
bool setNoDelay (bool flag)
 Sets NODELAY option on TCP socket, which can reduce latency for small packet sizes. More...
 
bool setNonBlock ()
 Set socket to nonblocking. Most importantly, calls to read() will return immediately, even if no data is available. More...
 
void setReadStringIgnoreReturn (bool ignore)
 Whether to ignore carriage return characters in readString or not.
 
bool setReuseAddress ()
 Set the reuse address value. More...
 
void setStringUseWrongEndChars (bool useWrongEndChars)
 Sets whether we use the wrong (legacy) end chars or not.
 
struct sockaddr_in * sockAddrIn ()
 Accessor for the sockaddr.
 
void transfer (ArSocket *s)
 Transfer ownership of a socket. More...
 
int write (const void *buff, size_t len)
 Write data to the socket. More...
 
int writeString (const char *str,...)
 Writes a string to the socket (adding end of line characters) More...
 
int writeStringPlain (const char *str)
 Same as writeString(), but no varargs.
 
 ~ArSocket ()
 Destructor.
 

Static Public Member Functions

static bool addrHost (struct in_addr &addr, char *host)
 Convert an address structure to a hostname string. More...
 
static std::string getHostName ()
 Get the localhost address.
 
static bool hostAddr (const char *host, struct in_addr &addr)
 Convert a hostname string to an address structure. More...
 
static unsigned int hostToNetOrder (int i)
 Convert an int from host byte order to network byte order.
 
static bool init ()
 Initialize the OS sockets system, if neccesary. More...
 
static void inToA (struct in_addr *addr, char *buff)
 Convert addr into string numerical address.
 
static size_t maxHostNameLen ()
 Max host name length.
 
static unsigned int netToHostOrder (int i)
 Convert an int from network byte order to host byte order.
 
static void shutdown ()
 Shutdown the OS sockets system, if neccesary. More...
 
static size_t sockAddrLen ()
 Size of the sockaddr.
 
static const char * toString (Type t)
 Converts the given socket type to a displayable text string (for debugging).
 

Static Public Attributes

static bool ourInitialized =true
 We're always initialized in Linux.
 

Protected Member Functions

void doStringEcho (void)
 internal function that echos strings from read string
 
void internalInit (void)
 
void separateHost (const char *rawHost, int rawPort, char *useHost, size_t useHostSize, int *port)
 
void setRawIPString (void)
 Sets the ip string internal function that sets the ip string from the inAddr.
 

Protected Attributes

bool myBadRead
 
bool myBadWrite
 
long myBytesRecvd
 
long myBytesSent
 
ArFunctormyCloseFunctor
 
bool myDoClose
 
Error myError
 
std::string myErrorStr
 
bool myErrorTracking
 
int myFD
 
std::string myIPString
 
ArTime myLastStringReadTime
 
bool myLogWriteStrings
 
bool myNonBlocking
 
char myRawIPString [128]
 
ArMutex myReadStringMutex
 
long myRecvs
 
long mySends
 
struct sockaddr_in mySin
 
bool myStringAutoEcho
 
char myStringBuf [5000]
 
char myStringBufEmpty [1]
 
bool myStringEcho
 
bool myStringGotComplete
 
bool myStringGotEscapeChars
 
bool myStringHaveEchoed
 
bool myStringIgnoreReturn
 
size_t myStringPos
 
size_t myStringPosLast
 
bool myStringWrongEndChars
 
Type myType
 
ArMutex myWriteStringMutex
 

Detailed Description

socket communication wrapper

ArSocket is a layer which allows you to use the sockets networking interface in an operating system independent manner. All of the standard commonly used socket functions are implemented such as open(), close(), connect(), accept(), read(), write(), hostToNetOrder(), netToHostOrder(). ArSocket extends some of these functions to set useful options (see method documentation for details). It also provides additional useful functions like writeString(), readString, setCloseCallback(), and more.

In Windows, the sockets subsystem needs to be initialized and shutdown by the program. So when a program starts it must call Aria::init() and call Aria::shutdown() when it exits. (Or, to only initialize the socket system, and not do any other global Aria initialization, use ArSocket::init() and ArSocket::shutdown().)

Some calls set an error code on failure in addition to returning false. This value is available from getError(). If getError() returns something other than NoErr, a text description of the error may be available from getErrorStr().

See also
socketServerExample.cpp
socketClientExample.cpp
Examples:
netServerExample.cpp, socketClientExample.cpp, and socketServerExample.cpp.

Constructor & Destructor Documentation

◆ ArSocket() [1/2]

ArSocket::ArSocket ( const char *  host,
int  port,
Type  type 
)

Constructor which immediately connects to a server as a client host Hostname or IP address of remote server port Port number on server Which IP protocol to use, type ArSocket::TCP or ArSocket::UDP.

Constructs the socket and connects it to the given host.

Parameters
hosthostname of the server to connect to
portport number of the server to connect to
typeprotocol type to use

◆ ArSocket() [2/2]

ArSocket::ArSocket ( int  port,
bool  doClose,
Type  type 
)

Constructor which immediately opens a port as a server port Port number to open.

Use a value greater than 1024. doClose Automatically close the port when ArSocket is destroyed (recommend using true) type Which IP protocol to use, ArSocket::TCP or ArSocket::UDP

Member Function Documentation

◆ accept()

bool ArSocket::accept ( ArSocket sock)

Accept a new connection.

Returns
true if there are no errors, false if there are errors... not that if you're in non-blocking mode and there is no socket to connect that is NOT an error, you'll want to check the getFD on the sock you pass in to see if it is actually a valid socket.
false and set error code and description string on failure
Examples:
socketServerExample.cpp.

◆ addrHost()

bool ArSocket::addrHost ( struct in_addr &  addr,
char *  host 
)
static

Convert an address structure to a hostname string.

Returns
false on failure

◆ close()

bool ArSocket::close ( void  )

Close the socket.

Returns
false and set error code and description string on failure
Examples:
socketClientExample.cpp, and socketServerExample.cpp.

◆ connect()

bool ArSocket::connect ( const char *  host,
int  port,
Type  type = TCP,
const char *  openOnIP = NULL 
)

Connect as a client to a server.

Returns
false and set error code and description string on failure
Examples:
socketClientExample.cpp.

◆ connectTo() [1/2]

bool ArSocket::connectTo ( const char *  host,
int  port 
)

Connect the socket to the given address.

Returns
false and set error code and description string on failure

◆ connectTo() [2/2]

bool ArSocket::connectTo ( struct sockaddr_in *  sin)

Connect the socket to the given address.

Returns
false and set error code and description string on failure

◆ copy()

bool ArSocket::copy ( int  fd,
bool  doclose 
)

Copy internal socket structures.

Copy socket structures.

Copy from one Socket to another will still have the first socket close the file descripter when it is destructed.

Returns
false and set error code and description string on failure.
false and set error code and description string on failure

◆ create()

bool ArSocket::create ( Type  type)

Simply create a port.

Returns
false and set error code and description string on failure

◆ findValidPort()

bool ArSocket::findValidPort ( int  startPort,
const char *  openOnIP = NULL 
)

Find the first valid unused port after startPort, and bind the socket to it.

Parameters
startPortfirst port to try
openOnIPIf given, only check ports open on the interface accociated with this address (Linux only)
Returns
false on error
false on failure

◆ getSockName()

bool ArSocket::getSockName ( )

Get socket information (socket "name"). Aspects of this "name" are accessible with sockAddrIn(), inAddr(), inPort()

Returns
false and set error code and description string on failure

◆ hostAddr()

bool ArSocket::hostAddr ( const char *  host,
struct in_addr &  addr 
)
static

Convert a hostname string to an address structure.

Returns
false on failure

◆ init()

bool ArSocket::init ( void  )
static

Initialize the OS sockets system, if neccesary.

In Windows, the networking subsystem needs to be initialized and shutdown individyaly by each program.

So when a program starts they will need to call the static function ArSocket::init() and call ArSocket::shutdown() when it exits. For programs that use Aria::init() and Aria::uninit() calling the ArSocket::init() and ArSocket::shutdown() is unnecessary. The Aria initialization functions take care of this. These functions do nothing in Linux.

Returns
false failure.

◆ open()

bool ArSocket::open ( int  port,
Type  type,
const char *  openOnIP = NULL 
)

Open a server port.

Opens a server port, that is, a port that is bound to a local port (and optionally, address) and listens for new incoming connections. Use accept() to wait for a new incoming connection from a client.

In additon, internally this method calls setLinger(0), setReuseAddress(), and setNonBlock() to turn on these options (having these on is particularly useful for servers).

Parameters
portPort number
typeArSocket::TCP or ArSocket::UDP.
openOnIPIf given, only bind to the interface accociated with this address (Linux only) (by default, all interfaces are used)
Returns
false and set error code and description string on failure
Examples:
socketServerExample.cpp.

◆ read()

int ArSocket::read ( void *  buff,
size_t  len,
unsigned int  msWait = 0 
)

Read data from the socket.

Parameters
buffbuffer to read into
lenhow many bytes to read
msWaitif 0, don't block, if > 0 wait this long for data
Returns
number of bytes read
Examples:
socketClientExample.cpp, and socketServerExample.cpp.

◆ readString()

char * ArSocket::readString ( unsigned int  msWait = 0)

Reads a string from the socket.

Note
This function can only read strings less than 512 characters long as it reads the characters into its own internal buffer (to compensate for some of the things the DOS telnet does).
Parameters
msWaitif 0, don't block, if > 0 wait this long for data
Returns
Data read, or an empty string (first character will be '\0') if no data was read. If there was an error reading from the socket, NULL is returned.

◆ recvFrom()

int ArSocket::recvFrom ( void *  msg,
int  len,
sockaddr_in *  sin 
)

Receive a message (short string) from the socket.

Normally, read() should be used instead. This is a wrapper around the recvfrom() system call.

◆ sendTo() [1/2]

int ArSocket::sendTo ( const void *  msg,
int  len 
)

Send a message (short string) on the socket.

Normally, write() should be used instead. This is a wrapper around the sendto() system call.

◆ sendTo() [2/2]

int ArSocket::sendTo ( const void *  msg,
int  len,
struct sockaddr_in *  sin 
)

Send a message (short string) on the socket.

Normally, write() should be used instead. This is a wrapper around the sendto() system call.

◆ setBroadcast()

bool ArSocket::setBroadcast ( )

Set broadcast value.

Returns
false and set error code and description string on failure.
false and set error code and description string on failure

◆ setLinger()

bool ArSocket::setLinger ( int  time)

Set the linger value.

Returns
false and set error code and description string on failure.
false and set error code and description string on failure

◆ setNoDelay()

bool ArSocket::setNoDelay ( bool  flag)

Sets NODELAY option on TCP socket, which can reduce latency for small packet sizes.

If this socket is a TCP socket, then set the TCP_NODELAY flag to 1, to disable the use of the Nagle algorithm (which waits until enough data is ready to send to fill a TCP frame, rather then sending the packet immediately).

If this socket is a TCP socket, then set the TCP_NODELAY flag, to disable the use of the Nagle algorithm (which waits until enough data is ready to send to fill a TCP frame, rather then sending the packet immediately).

Parameters
flagtrue to turn on NoDelay, false to turn it off.
Returns
true of the flag was successfully set, false if there was an error or this socket is not a TCP socket.
true of the flag was successfully set, false if there was an error or this socket is not a TCP socket.

◆ setNonBlock()

bool ArSocket::setNonBlock ( )

Set socket to nonblocking. Most importantly, calls to read() will return immediately, even if no data is available.

Returns
false and set error code and description string on failure.
false and set error code and description string on failure

◆ setReuseAddress()

bool ArSocket::setReuseAddress ( )

Set the reuse address value.

Returns
false and set error code and description string on failure.
false and set error code and description string on failure

◆ shutdown()

void ArSocket::shutdown ( )
static

Shutdown the OS sockets system, if neccesary.

In Windows, the networking subsystem needs to be initialized and shutdown individyaly by each program.

So when a program starts they will need to call the static function ArSocket::init() and call ArSocket::shutdown() when it exits. For programs that use Aria::init() and Aria::uninit() calling the ArSocket::init() and ArSocket::shutdown() is unnecessary. The Aria initialization functions take care of this. These functions do nothing in Linux.

◆ transfer()

void ArSocket::transfer ( ArSocket s)
inline

Transfer ownership of a socket.

transfer() will transfer ownership to this socket. The input socket will no longer close the file descriptor when it is destructed.

◆ write()

int ArSocket::write ( const void *  buff,
size_t  len 
)

Write data to the socket.

Parameters
buffbuffer to write from
lenhow many bytes to write
Returns
number of bytes written
Examples:
socketClientExample.cpp, and socketServerExample.cpp.

◆ writeString()

int ArSocket::writeString ( const char *  str,
  ... 
)

Writes a string to the socket (adding end of line characters)

Java and Python Wrappers: Not available in Java or Python wrapper libraries.

See also
writeStringPlain()
Examples:
netServerExample.cpp.

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