PChannel Class Reference

#include <channel.h>

Inheritance diagram for PChannel:

PObject PConsoleChannel PFile PIndirectChannel PMonitoredSocketChannel PPipeChannel PQueueChannel PSerialChannel PSocket PSoundChannel List of all members.

Miscellaneous functions

enum  ShutdownValue { ShutdownRead = 0, ShutdownWrite = 1, ShutdownReadAndWrite = 2 }
virtual BOOL Close ()
virtual BOOL Shutdown (ShutdownValue option)
BOOL SetBufferSize (PINDEX newSize)
BOOL SendCommandString (const PString &command)
void AbortCommandString ()

Error functions

enum  Errors {
  NoError, NotFound, FileExists, DiskFull,
  AccessDenied, DeviceInUse, BadParameter, NoMemory,
  NotOpen, Timeout, Interrupted, BufferTooSmall,
  Miscellaneous, ProtocolFailure, NumNormalisedErrors
}
enum  ErrorGroup { LastReadError, LastWriteError, LastGeneralError, NumErrorGroups }
Errors GetErrorCode (ErrorGroup group=NumErrorGroups) const
int GetErrorNumber (ErrorGroup group=NumErrorGroups) const
virtual PString GetErrorText (ErrorGroup group=NumErrorGroups) const
static PString GetErrorText (Errors lastError, int osError=0)

Scattered read/write functions

typedef std::vector< SliceVectorOfSlice
virtual BOOL Read (const VectorOfSlice &slices)
virtual BOOL Write (const VectorOfSlice &slices)

Public Types

enum  PXBlockType { PXReadBlock, PXWriteBlock, PXAcceptBlock, PXConnectBlock }

Public Member Functions

BOOL SetErrorValues (Errors errorCode, int osError, ErrorGroup group=LastGeneralError)
Overrides from class PObject
virtual Comparison Compare (const PObject &obj) const
virtual PINDEX HashFunction () const
Information functions
virtual BOOL IsOpen () const
virtual PString GetName () const
int GetHandle () const
virtual PChannelGetBaseReadChannel () const
virtual PChannelGetBaseWriteChannel () const
Reading functions
void SetReadTimeout (const PTimeInterval &time)
PTimeInterval GetReadTimeout () const
virtual BOOL Read (void *buf, PINDEX len)
virtual PINDEX GetLastReadCount () const
virtual int ReadChar ()
BOOL ReadBlock (void *buf, PINDEX len)
PString ReadString (PINDEX len)
virtual BOOL ReadAsync (void *buf, PINDEX len)
virtual void OnReadComplete (void *buf, PINDEX len)
Writing functions
void SetWriteTimeout (const PTimeInterval &time)
PTimeInterval GetWriteTimeout () const
virtual BOOL Write (const void *buf, PINDEX len)
virtual PINDEX GetLastWriteCount () const
BOOL WriteChar (int c)
BOOL WriteString (const PString &str)
virtual BOOL WriteAsync (const void *buf, PINDEX len)
virtual void OnWriteComplete (const void *buf, PINDEX len)

Static Public Member Functions

static BOOL ConvertOSError (int libcReturnValue, Errors &lastError, int &osError)

Protected Member Functions

 PChannel (const PChannel &)
PChanneloperator= (const PChannel &)
virtual BOOL ConvertOSError (int libcReturnValue, ErrorGroup group=LastGeneralError)
int ReadCharWithTimeout (PTimeInterval &timeout)
BOOL ReceiveCommandString (int nextChar, const PString &reply, PINDEX &pos, PINDEX start)
BOOL PXSetIOBlock (PXBlockType type, const PTimeInterval &timeout)
int PXClose ()

Protected Attributes

int os_handle
 The operating system file handle return by standard open() function.
Errors lastErrorCode [NumErrorGroups+1]
 The platform independant error code.
int lastErrorNumber [NumErrorGroups+1]
 The operating system error number (eg as returned by errno).
PINDEX lastReadCount
 Number of byte last read by the Read() function.
PINDEX lastWriteCount
 Number of byte last written by the Write() function.
PTimeInterval readTimeout
 Timeout for read operations.
PTimeInterval writeTimeout
 Timeout for write operations.
PString channelName
PMutex px_threadMutex
PXBlockType px_lastBlockType
PThreadpx_readThread
PThreadpx_writeThread
PMutex px_writeMutex
PThreadpx_selectThread
PMutex px_selectMutex

Classes

struct  Slice

Detailed Description

Abstract class defining I/O channel semantics. An I/O channel can be a serial port, pipe, network socket or even just a simple file. Anything that requires opening and closing then reading and/or writing from.

A descendent would typically have constructors and an Open()# function which enables access to the I/O channel it represents. The Read()# and Write()# functions would then be overridden to the platform and I/O specific mechanisms required.

The general model for a channel is that the channel accepts and/or supplies a stream of bytes. The access to the stream of bytes is via a set of functions that allow certain types of transfer. These include direct transfers, buffered transfers (via iostream) or asynchronous transfers.

The model also has the fundamental state of the channel being { open} or { closed}. A channel instance that is closed contains sufficient information to describe the channel but does not allocate or lock any system resources. An open channel allocates or locks the particular system resource. The act of opening a channel is a key event that may fail. In this case the channel remains closed and error values are set.


Member Typedef Documentation

typedef std::vector<Slice> PChannel::VectorOfSlice


Member Enumeration Documentation

enum PChannel::ShutdownValue

Enumerator:
ShutdownRead 
ShutdownWrite 
ShutdownReadAndWrite 

enum PChannel::Errors

Normalised error codes. The error result of the last file I/O operation in this object.

Enumerator:
NoError 
NotFound  Open fail due to device or file not found.
FileExists  Open fail due to file already existing.
DiskFull  Write fail due to disk full.
AccessDenied  Operation fail due to insufficient privilege.
DeviceInUse  Open fail due to device already open for exclusive use.
BadParameter  Operation fail due to bad parameters.
NoMemory  Operation fail due to insufficient memory.
NotOpen  Operation fail due to channel not being open yet.
Timeout  Operation failed due to a timeout.
Interrupted  Operation was interrupted.
BufferTooSmall  Operations buffer was too small for data.
Miscellaneous  Miscellaneous error.
ProtocolFailure  High level protocol failure.
NumNormalisedErrors 

enum PChannel::ErrorGroup

Error groups. To aid in multithreaded applications where reading and writing may be happening simultaneously, read and write errors are separated from other errors.

Enumerator:
LastReadError  Error during Read() operation.
LastWriteError  Error during Write() operation.
LastGeneralError  Error during other operation, eg Open().
NumErrorGroups 

enum PChannel::PXBlockType

Enumerator:
PXReadBlock 
PXWriteBlock 
PXAcceptBlock 
PXConnectBlock 


Constructor & Destructor Documentation

PChannel::PChannel (  ) 

Create the channel.

PChannel::~PChannel (  ) 

Close down the channel.

PINLINE PChannel::PChannel ( const PChannel  )  [protected]

PChannel::PChannel (  ) 

Create the channel.

PChannel::~PChannel (  ) 

Close down the channel.


Member Function Documentation

virtual Comparison PChannel::Compare ( const PObject obj  )  const [virtual]

Get the relative rank of the two strings. The system standard function, eg strcmp(), is used.

Returns:
comparison of the two objects, EqualTo# for same, LessThan# for obj# logically less than the object and GreaterThan# for obj# logically greater than the object.
Parameters:
obj  Other PString to compare against.

Reimplemented from PObject.

Reimplemented in PFile, PIndirectChannel, PPipeChannel, and PMemoryFile.

virtual PINDEX PChannel::HashFunction (  )  const [virtual]

Calculate a hash value for use in sets and dictionaries.

The hash function for strings will produce a value based on the sum of the first three characters of the string. This is a fairly basic function and make no assumptions about the string contents. A user may descend from PString and override the hash function if they can take advantage of the types of strings being used, eg if all strings start with the letter 'A' followed by 'B or 'C' then the current hash function will not perform very well.

Returns:
hash value for string.

Reimplemented from PObject.

virtual BOOL PChannel::IsOpen (  )  const [virtual]

Determine if the channel is currently open. This indicates that read and write operations can be executed on the channel. For example, in the PFile# class it returns if the file is currently open.

Returns:
TRUE if the channel is open.

Reimplemented in PIndirectChannel, PSoundChannel, and PMonitoredSocketChannel.

virtual PString PChannel::GetName (  )  const [virtual]

Get the platform and I/O channel type name of the channel. For example, it would return the filename in PFile# type channels.

Returns:
the name of the channel.

Reimplemented in PConsoleChannel, PFile, PIndirectChannel, PIPSocket, PIPXSocket, PPipeChannel, and PSoundChannel.

PINLINE int PChannel::GetHandle (  )  const

Get the integer operating system handle for the channel.

Returns:
standard OS descriptor integer.

Reimplemented in PSoundChannel.

virtual PChannel* PChannel::GetBaseReadChannel (  )  const [virtual]

Get the base channel of channel indirection using PIndirectChannel. This function returns the eventual base channel for reading of a series of indirect channels provided by descendents of PIndirectChannel#.

The behaviour for this function is to return "this".

Returns:
Pointer to base I/O channel for the indirect channel.

Reimplemented in PIndirectChannel.

virtual PChannel* PChannel::GetBaseWriteChannel (  )  const [virtual]

Get the base channel of channel indirection using PIndirectChannel. This function returns the eventual base channel for writing of a series of indirect channels provided by descendents of PIndirectChannel#.

The behaviour for this function is to return "this".

Returns:
Pointer to base I/O channel for the indirect channel.

Reimplemented in PIndirectChannel.

PINLINE void PChannel::SetReadTimeout ( const PTimeInterval time  ) 

Set the timeout for read operations. This may be zero for immediate return of data through to PMaxTimeInterval# which will wait forever for the read request to be filled.

Note that this function may not be available, or meaningfull, for all channels. In that case it is set but ignored.

Parameters:
time  The new time interval for read operations.

PINLINE PTimeInterval PChannel::GetReadTimeout (  )  const

Get the timeout for read operations. Note that this function may not be available, or meaningfull, for all channels. In that case it returns the previously set value.

Returns:
time interval for read operations.

virtual BOOL PChannel::Read ( void *  buf,
PINDEX  len 
) [virtual]

Low level read from the channel. This function may block until the requested number of characters were read or the read timeout was reached. The GetLastReadCount() function returns the actual number of bytes read.

The GetErrorCode() function should be consulted after Read() returns FALSE to determine what caused the failure.

Returns:
TRUE indicates that at least one character was read from the channel. FALSE means no bytes were read due to timeout or some other I/O error.
Parameters:
buf  Pointer to a block of memory to receive the read bytes.
len  Maximum number of bytes to read into the buffer.

Reimplemented in PEthSocket, PFile, PIndirectChannel, PPipeChannel, PSocket, PSoundChannel, PTCPSocket, PUDPSocket, PDelayChannel, PInternetProtocol, PMemoryFile, PMonitoredSocketChannel, PSSLChannel, PWAVFile, PQueueChannel, and PTelnetSocket.

virtual PINDEX PChannel::GetLastReadCount (  )  const [virtual]

Get the number of bytes read by the last Read() call. This will be from 0 to the maximum number of bytes as passed to the Read() call.

Note that the number of bytes read may often be less than that asked for. Aside from the most common case of being at end of file, which the applications semantics may regard as an exception, there are some cases where this is normal. For example, if a PTextFile channel on the MSDOS platform is read from, then the translation of CR/LF pairs to
characters will result in the number of bytes returned being less than the size of the buffer supplied.

Returns:
the number of bytes read.

Reimplemented in PSoundChannel.

virtual int PChannel::ReadChar (  )  [virtual]

Read a single 8 bit byte from the channel. If one was not available within the read timeout period, or an I/O error occurred, then the function gives with a -1 return value.

Returns:
byte read or -1 if no character could be read.

BOOL PChannel::ReadBlock ( void *  buf,
PINDEX  len 
)

Read len bytes into the buffer from the channel. This function uses Read(), so most remarks pertaining to that function also apply to this one. The only difference being that this function will not return until all of the bytes have been read, or an error occurs.

Returns:
TRUE if the read of len# bytes was sucessfull.
Parameters:
buf  Pointer to a block of memory to receive the read bytes.
len  Maximum number of bytes to read into the buffer.

PString PChannel::ReadString ( PINDEX  len  ) 

Read len# character into a string from the channel. This function simply uses ReadBlock(), so all remarks pertaining to that function also apply to this one.

Returns:
String that was read.

virtual BOOL PChannel::ReadAsync ( void *  buf,
PINDEX  len 
) [virtual]

Begin an asynchronous read from channel. The read timeout is used as in other read operations, in this case calling the OnReadComplete() function.

Note that if the channel is not capable of asynchronous read then this will do a sychronous read is in the Read() function with the addition of calling the OnReadComplete() before returning.

Returns:
TRUE if the read was sucessfully queued.
Parameters:
buf  Pointer to a block of memory to receive the read bytes.
len  Maximum number of bytes to read into the buffer.

virtual void PChannel::OnReadComplete ( void *  buf,
PINDEX  len 
) [virtual]

User callback function for when a ReadAsync()# call has completed or timed out. The original pointer to the buffer passed in ReadAsync() is passed to the function.

Parameters:
buf  Pointer to a block of memory that received the read bytes.
len  Actual number of bytes to read into the buffer.

PINLINE void PChannel::SetWriteTimeout ( const PTimeInterval time  ) 

Set the timeout for write operations to complete. This may be zero for immediate return through to PMaxTimeInterval which will wait forever for the write request to be completed.

Note that this function may not be available, or meaningfull, for all channels. In this case the parameter is et but ignored.

Parameters:
time  The new time interval for write operations.

PINLINE PTimeInterval PChannel::GetWriteTimeout (  )  const

Get the timeout for write operations to complete. Note that this function may not be available, or meaningfull, for all channels. In that case it returns the previously set value.

Returns:
time interval for writing.

virtual BOOL PChannel::Write ( const void *  buf,
PINDEX  len 
) [virtual]

Low level write to the channel. This function will block until the requested number of characters are written or the write timeout is reached. The GetLastWriteCount() function returns the actual number of bytes written.

The GetErrorCode() function should be consulted after Write() returns FALSE to determine what caused the failure.

Returns:
TRUE if at least len bytes were written to the channel.
Parameters:
buf  Pointer to a block of memory to write.
len  Number of bytes to write.

Reimplemented in PEthSocket, PFile, PIndirectChannel, PPipeChannel, PSoundChannel, PTCPSocket, PUDPSocket, PDelayChannel, PRFC822Channel, PInternetProtocol, PMemoryFile, PMonitoredSocketChannel, PSSLChannel, PWAVFile, PQueueChannel, and PTelnetSocket.

virtual PINDEX PChannel::GetLastWriteCount (  )  const [virtual]

Get the number of bytes written by the last Write() call.

Note that the number of bytes written may often be less, or even more, than that asked for. A common case of it being less is where the disk is full. An example of where the bytes written is more is as follows. On a PTextFile# channel on the MSDOS platform, there is translation of
to CR/LF pairs. This will result in the number of bytes returned being more than that requested.

Returns:
the number of bytes written.

Reimplemented in PSoundChannel.

BOOL PChannel::WriteChar ( int  c  ) 

Write a single character to the channel. This function simply uses the Write() function so all comments on that function also apply.

Note that this asserts if the value is not in the range 0..255.

Returns:
TRUE if the byte was successfully written.

BOOL PChannel::WriteString ( const PString str  ) 

Write a string to the channel. This function simply uses the Write() function so all comments on that function also apply.

Returns:
TRUE if the character written.

virtual BOOL PChannel::WriteAsync ( const void *  buf,
PINDEX  len 
) [virtual]

Begin an asynchronous write from channel. The write timeout is used as in other write operations, in this case calling the OnWriteComplete() function. Note that if the channel is not capable of asynchronous write then this will do a sychronous write as in the Write() function with the addition of calling the OnWriteComplete() before returning.

Returns:
TRUE of the write operation was succesfully queued.
Parameters:
buf  Pointer to a block of memory to write.
len  Number of bytes to write.

virtual void PChannel::OnWriteComplete ( const void *  buf,
PINDEX  len 
) [virtual]

User callback function for when a WriteAsync() call has completed or timed out. The original pointer to the buffer passed in WriteAsync() is passed in here and the len parameter is the actual number of characters written.

Parameters:
buf  Pointer to a block of memory to write.
len  Number of bytes to write.

virtual BOOL PChannel::Close (  )  [virtual]

Close the channel, shutting down the link to the data source.

Returns:
TRUE if the channel successfully closed.

Reimplemented in PConsoleChannel, PEthSocket, PFile, PIndirectChannel, PPipeChannel, PSerialChannel, PSoundChannel, PFTPClient, PSMTPClient, PPOP3Client, PRFC822Channel, PModem, PMonitoredSocketChannel, PSSLChannel, PWAVFile, and PQueueChannel.

virtual BOOL PChannel::Shutdown ( ShutdownValue  option  )  [virtual]

Close one or both of the data streams associated with a channel.

The default behavour is to do nothing and return FALSE.

Returns:
TRUE if the shutdown was successfully performed.

Reimplemented in PIndirectChannel, PSocket, and PSSLChannel.

BOOL PChannel::SetBufferSize ( PINDEX  newSize  ) 

Set the iostream buffer size for reads and writes.

Returns:
TRUE if the new buffer size was set.
Parameters:
newSize  New buffer size

BOOL PChannel::SendCommandString ( const PString command  ) 

Send a command meta-string. A meta-string is a string of characters that may contain escaped commands. The escape command is the \ as in the C language.

The escape commands are: {description} [# #] alert (ascii value 7) [# #] backspace (ascii value 8) [##] formfeed (ascii value 12) [#
#] newline (ascii value 10) [##] return (ascii value 13) [##] horizontal tab (ascii value 9) [##] vertical tab (ascii value 11) [#\#] backslash [##] where ooo is octal number, ascii value ooo [##] where hh is hex number (ascii value 0xhh) [##] null character (ascii zero) [##] delay for n seconds [##] delay for n milliseconds [##] characters following this, up to a command or the end of string, are to be sent to modem [##] characters following this, up to a , or another or the end of the string are expected back from the modem. If the string is not received within n seconds, a failed command is registered. The exception to this is if the command is at the end of the string or the next character in the string is the , or in which case all characters are ignored from the modem until n seconds of no data. [##] as for above but timeout is in milliseconds. {description}

Returns:
TRUE if the command string was completely processed.
Parameters:
command  Command to send to the channel

PINLINE void PChannel::AbortCommandString (  ) 

Abort a command string that is in progress. Note that as the SendCommandString() function blocks the calling thread when it runs, this can only be called from within another thread.

PINLINE PChannel::Errors PChannel::GetErrorCode ( ErrorGroup  group = NumErrorGroups  )  const

Get normalised error code. Return the error result of the last file I/O operation in this object.

Returns:
Normalised error code.
Parameters:
group  Error group to get

PINLINE int PChannel::GetErrorNumber ( ErrorGroup  group = NumErrorGroups  )  const

Get OS errro code. Return the operating system error number of the last file I/O operation in this object.

Returns:
Operating System error code.
Parameters:
group  Error group to get

virtual PString PChannel::GetErrorText ( ErrorGroup  group = NumErrorGroups  )  const [virtual]

Get error message description. Return a string indicating the error message that may be displayed to the user. The error for the last I/O operation in this object is used.

Returns:
Operating System error description string.
Parameters:
group  Error group to get

Reimplemented in PIndirectChannel, and PSSLChannel.

static PString PChannel::GetErrorText ( Errors  lastError,
int  osError = 0 
) [static]

Get error message description. Return a string indicating the error message that may be displayed to the user. The osError# parameter is used unless zero, in which case the lastError# parameter is used.

Returns:
Operating System error description string.
Parameters:
lastError  Error code to translate.
osError  OS error number to translate.

static BOOL PChannel::ConvertOSError ( int  libcReturnValue,
Errors lastError,
int &  osError 
) [static]

Convert an operating system error into platform independent error. This will set the lastError and osError member variables for access by GetErrorCode() and GetErrorNumber().

Returns:
TRUE if there was no error.

virtual BOOL PChannel::Read ( const VectorOfSlice slices  )  [virtual]

Low level scattered read from the channel. This is identical to Read except that the data will be read into a series of scattered memory slices. By default, this call will default to calling Read multiple times, but this may be implemented by operating systems to do a real scattered read

Returns:
TRUE indicates that at least one character was read from the channel. FALSE means no bytes were read due to timeout or some other I/O error.

virtual BOOL PChannel::Write ( const VectorOfSlice slices  )  [virtual]

Low level scattered write to the channel. This is identical to Write except that the data will be written from a series of scattered memory slices. By default, this call will default to calling Write multiple times, but this can be actually implemented by operating systems to do a real scattered write

Returns:
TRUE indicates that at least one character was read from the channel. FALSE means no bytes were read due to timeout or some other I/O error.

PINLINE PChannel & PChannel::operator= ( const PChannel  )  [protected]

virtual BOOL PChannel::ConvertOSError ( int  libcReturnValue,
ErrorGroup  group = LastGeneralError 
) [protected, virtual]

Convert an operating system error into platform independent error. The internal error codes are set by this function. They may be obtained via the GetErrorCode()# and GetErrorNumber()# functions.

Returns:
TRUE if there was no error.
Parameters:
group  Error group to set

Reimplemented in PSSLChannel.

BOOL PChannel::SetErrorValues ( Errors  errorCode,
int  osError,
ErrorGroup  group = LastGeneralError 
)

Set error values to those specified. Return TRUE if errorCode is NoError, FALSE otherwise

Parameters:
errorCode  Error code to translate.
osError  OS error number to translate.
group  Error group to set

int PChannel::ReadCharWithTimeout ( PTimeInterval timeout  )  [protected]

Read a character with specified timeout. This reads a single character from the channel waiting at most the amount of time specified for it to arrive. The timeout# parameter is adjusted for amount of time it actually took, so it can be used for a multiple character timeout.

Returns:
TRUE if there was no error.

BOOL PChannel::ReceiveCommandString ( int  nextChar,
const PString reply,
PINDEX &  pos,
PINDEX  start 
) [protected]

BOOL PChannel::PXSetIOBlock ( PXBlockType  type,
const PTimeInterval timeout 
) [protected]

int PChannel::PXClose (  )  [protected]


Member Data Documentation

int PChannel::os_handle [protected]

The operating system file handle return by standard open() function.

Errors PChannel::lastErrorCode[NumErrorGroups+1] [protected]

The platform independant error code.

int PChannel::lastErrorNumber[NumErrorGroups+1] [protected]

The operating system error number (eg as returned by errno).

PINDEX PChannel::lastReadCount [protected]

Number of byte last read by the Read() function.

PINDEX PChannel::lastWriteCount [protected]

Number of byte last written by the Write() function.

PTimeInterval PChannel::readTimeout [protected]

Timeout for read operations.

PTimeInterval PChannel::writeTimeout [protected]

Timeout for write operations.

PString PChannel::channelName [protected]

PMutex PChannel::px_threadMutex [protected]

PXBlockType PChannel::px_lastBlockType [protected]

PThread* PChannel::px_readThread [protected]

PThread* PChannel::px_writeThread [protected]

PMutex PChannel::px_writeMutex [protected]

PThread* PChannel::px_selectThread [protected]

PMutex PChannel::px_selectMutex [protected]


The documentation for this class was generated from the following files:
Generated on Fri Mar 7 06:25:04 2008 for PTLib by  doxygen 1.5.1