The Socket Class in oScript - Implementing a Server in the Content Server
The Socket Package offers a small set of built-ins enabling access to network socket connections through OScript. Server-style sockets which listen for incoming connection requests may even be implemented. The Socket built-ins are extremely easy to use once understood :-)
This class is quite important, you can realize an server (html or ftp) inside the Content Server or send some JSON data to this server using Socket.
The major functionalities offered by the Socket package are the following:
Socket sock = Socket.Create() Integer nlines = 0 String result
Socket.Connect( sock, "www.opentext.com", 80 ) Socket.Write( sock, "GET /index.html HTTP/1.0" ) Socket.Write( sock, Web.CRLF ) Socket.Write( sock, Web.CRLF ) Socket.Flush( sock )
while ( !IsError( result = Socket.Read( sock ) ) ) Echo( result ) nlines += 1 end
Socket.Close( sock )
Echo( "--Done. Read ", nlines, " lines." ) The output for the example on one run was (truncated):
HTTP/1.1 200 OK Date: Sat, 31 Oct 2010 01:35:13 GMT Server: Apache/1.8.2 (Unix) Last-Modified: Thu, 29 Oct 2010 18:55:13 GMT ETag: "425e-3e0c-3638ba11" Accept-Ranges: bytes Content-Length: 15884 Connection: close Content-Type: text/html
Example
This is an example of a webserver running as the Function Server().
Function void Server()
Integer port = 2326 // Port to listen on
Boolean status = False // True upon request Accept()
Boolean dataread = False // True when data read
Socket server = Socket.Create() // Listening server socket
Socket request = Socket.Create() // Accepted request socket.
Integer ticks = Date.Tick() // Time Listen() started
Integer maxwait = 10 // Max seconds to listen
String s
Socket.Listen( server, port )
Echo( "Socket waiting for Accept() on port ", port, "..." )
// Listen for a limited amount of time (maxwait seconds).
while ( !status && ( Date.Tick() - ticks < maxwait * 1000 ) )
status = Socket.Accept( request, server )
end
// Was a request was made and accepted?
if ( !status )
// No, the listen timed-out
Echo( "Listen time-out after ", maxwait, " seconds." )
else
Echo( "Reading..." )
// Read input waiting on the socket.
while ( !IsError( s = Socket.Read( request ) ) )
if ( Length( s ) <= 0 )
if ( !dataread )
// The socket is not ready for reading.
// Wait for input.
else
// The input is exhausted. Done reading.
break
end
else
Echo( 'Read "', s, '"' )
// Echo the read input back to sender.
Socket.Write( request, s )
dataread = True
end
end
// Close the connection request acceptance socket.
Socket.Close( request )
Echo( "Done." )
end
Echo( "Closing Server." )
Socket.Close( server )
end
Class Methods
Accept
Boolean Accept( Socket accept, Socket request ) - Accepts a connection request with a specified Socket. A request must be accepted before data can be read and written.
Parameters
accept - A fresh, unconnected Socket which will accept request.
request - The Socket to which connection request was made, which has been assigned to listen on a given port with Socket.Listen().
Returns:
True if the connection was successfully accepted, False otherwise.
Example
Behavior is undefined, and possibly catastrophic, if accept is an old, unclosed Socket, or request is not a Socket which which has been assigned to listen as a server socket with Socket.Listen().
Close
Boolean Close( Socket sock ) - Closes the specified socket, after flushing it.
Parameters
sock - The Socket to close.
Returns:
True if the socket was successfully closed, False otherwise.
CompareIpAddresses
Integer CompareIpAddresses( String addr1, String addr2 )
Compares two IPv4 or IPv6 addresses.
Parameters
addr1 - an IP address to compare
addr2 - the other IP address to compare
Returns:
Zero if the addresses are equal, non-zero otherwise.
Example
The addresses given must be the same format (IPv4 or IPv6). It is invalid to compare an IPv6 address to an IPv4 address.
However, you can compare an IPv4-mapped IPv6 address ("::ffff:127.0.0.1") with an IPv4 ("127.0.0.1") address.
Connect
Boolean Connect( Socket sock, String host, Integer port )
Attempts to connect a Socket to the specified host name and port number.
Parameters
sock - The Socket to connect.
host - The String name of the host.
port - The port number to which the connection should be made, which should be a positive Integer less than or equal to 65535.
Returns:
True if the Connection was successful, false or Error otherwise.
Example
Here is a short example which uses Socket.Connect() to determine the IP address of the host "www.opentext.com":
Socket sock = Socket.Create()
String host = "www.opentext.com"
Integer port = 2244
Socket.Connect( sock, host, 80 )
Echo( "Host IP = ", sock.( Socket.pPeerIPAddress ) )
Socket.Close( sock )
The output of the example is:
Host IP = 204.138.115.98
Create
Socket Create( [Dynamic featurename], [Dynamic callbackobj] )
Creates a new Socket. The optional arguments are for internal use only.
Parameters
featurename - The name of a Script callback feature in callbackobj to invoke when a connection request is made or data is available for reading. For internal OpenText use only.
callbackobj - An Object with a callback Script feature featurename. For internal OpenText use only.
Returns:
The new Socket.
Example
For internal use only: the Script should contain a void Function taking a Dynamic argument which will be a List. The first List element will be the message constant, either Socket.ConnectRequest or Socket.ReadReady. The second element will be the socket that caused the callback. Note that a Connection Request must be accepted with Socket.Accept() before data can be read or written.
Flush
Void Flush( Socket sock ) - Flushes the output buffer of the specified Socket.
Parameters
sock - The Socket to flush.
Returns:
GetAddrByName
String GetAddrByName( String host ) - Returns a string of the IP address resolved for the given hostname.
Parameters
host - The String name of the host.
Recommended by LinkedIn
Returns:
Resolved IP address. An empty String is returned if the address could not be resolved.
Listen
Boolean Listen( Socket sock, Integer port ) - Assigns the socket to listen on the given port.
Parameters
sock - The Socket to assign to listen
port - The port number on which the Socket should listen, which should be a positive value less than or equal to 65535.
Returns:
True if the Socket has successfully been assigned to listen on the given port, False if not (the socket may have already been assigned to listen).
Read
String Read( Socket sock ) - Reads available data from the specified Socket into a String until input is exhausted or the input buffer is full.
Parameters
sock - The Socket to read from.
Returns:
The String read, which may be of zero length if no input was available for reading, otherwise Error if the Socket could not be read, possibly due to end of file.
ReadBytes
Bytes ReadBytes( Socket sock ) - Reads available data from the specified Socket into a Bytes until input is exhausted or the input buffer is full.
Parameters
sock - The Socket to read from.
Returns:
The Bytes read, which may be of zero length if no input was available for reading, otherwise Error if the Socket could not be read, possibly due to end of file.
StreamBytesUntil
List StreamBytesUntil( Socket sock, Dynamic token, [Integer maxlength], [Integer msDelay] ) - Reads a Bytes from a Socket until either input matching token is read or maxlength number of bytes are read. Note that the Socket.pStreaming attribute must be set to true on the Socket to make it a stream Socket before this operation may be performed.
Parameters
sock - The stream Socket from which input will be read until either token is encountered, or maxlength bytes have been read.
token - The token Bytes to read until.
maxlength - If specified, the maximum number of bytes read before returning if token is not encountered. The default is a reasonable buffer size (4096).
msDelay - If specified, the millisecond delay between read tries, this will allow clients to wait for input without being as much of a CPU hog.
Returns:
The Bytes read, or Error.
StreamUntil
List StreamUntil( Socket sock, [Dynamic token], [Integer maxlength], [Integer msDelay] ) - Reads a String from a Socket until either input matching token is read or maxlength number of bytes are read. Note that the Socket.pStreaming attribute must be set to true on the Socket to make it a stream Socket before this operation may be performed.
Parameters
sock - The Socket from which a String will be read.
token - If specified, the token String to read until. The default is the empty String, meaning all available input is read.
maxlength - If specified, the maximum number of bytes read before returning if token is not encountered. The default is a reasonable buffer size (4096).
msDelay - If specified, the millisecond delay between read tries, this will allow clients to wait for input without being as much of a CPU hog.
Returns:
The String read, or Error.
Write
Boolean Write( Socket sock, Dynamic value ) - Writes a String or the contents of a Bytes to the given Socket.
Parameters
sock - The Socket to which the data is written.
value - A String or Bytes to write to the Socket.
Returns:
True if the value was successfully written to the Socket, False otherwise or Error.
Class Attributes
ConnectRequest - The callback constant indicating a connection has been made.
E_BufferTooSmall - An Error caused by too small a buffer used during a read.
E_EndOfFile - An Error caused due to end of file during a read.
E_Error - A generic Socket Error.
E_InstallError - Your networking software may have been incorrectly installed. Please check your installation notes.
E_UserCancelled - An Error caused by the user canceling the socket read or write.
kSecurityNone - Security constant indicating no security.
kSecuritySSL2 - Security constant indicating SSL2 security.
kSecuritySSL3 - Security constant indicating SSL3 security.
kServiceIdLLi - Service id for a Content Server request.
kServiceIdPing - Service id for a ping request.
kServiceIdStatus - Service id for a status request
ReadReady - The callback constant indicating a connection has been accepted and is now ready for reading.
SocketType - Type ID for a Socket interface.
Instance Attributes
pBlocking - True if block on input.
pPeerIPAddress - The String IP address of the connection, if connected, Undefined otherwise.
pPeerPort - The Integer Port of the connection, if connected, Undefined otherwise.
pReadTimeout - The Socket read timeout in milliseconds.
pSecurity - The security layer used by the Socket.
pStreaming - True if the Socket should behave like a stream.